Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django: class-view lacking attribute COOKIES

I am currently playing around with REST and backbone.js and ran into this issue:

'LoginView' object has no attribute 'COOKIES'

Here comes the following code for might have caused the problem. I have commented out a few things in the javascript, since I wanted it to load directly to the server instead, but I thought it would be just as good to bring it along.

I can also add that I have checked for the csrf-token in the form and it is there.

views.py

class LoginView(TemplateView):
    authentication_form=LoginForm
    form_class = LoginForm
    redirect_field_name=REDIRECT_FIELD_NAME
    template_name = 'front/login.html'
    initial = {'key': 'value'}

    def get(self, request, *args, **kwargs):
        form = self.form_class(initial=self.initial)
        return render(request, self.template_name, {'form': form})

    @method_decorator(sensitive_post_parameters())
    @csrf_protect
    @never_cache
    @api_view(['GET', 'POST'])
    def post(self, request, *args, **kwargs):
        form = self.form_class(request.POST)
        print request.COOKIES('csrftoken')
        print request.POST.get('csrfmiddlewaretoken')
        if form.is_valid():
            #if not is_safe_url(url=redirect_to, host=request.get_host()):
            #   redirect_to = resolve_url(settings.LOGIN_REDIRECT_URL)
            print request.POST.get('email')
            #user = self.get_user(request.POST.get('email'))
            #print user
            #auth = UserDataAuthentication(request, user)
            user = authenticate(email=request.POST.get('email'), password=request.POST.get('password'))
            if user is not None:
                auth_login(request, user)
                return Response(user, status=status.HTTP_201_CREATED)
        return HttpResponseRedirect('/login/')

login.js

var csrftoken = $('meta[name="csrf-token"]').attr('content');
SigninView = Backbone.View.extend({
    events: {
        //"click button[type=submit]": "sendRequest"
    },
    sendRequest: function( event ){
        //event.preventDefault();
        var csrftoken = $.cookie('csrftoken');
        var url = '/login/validate/';
        var email = $("#id_email").val();
        var password = $("#id_password").val();
        var items = {
                        email: email,
                        password: password,
                        csrfmiddlewaretoken: csrftoken
                    };      
        console.log(csrftoken);
        $.ajax({
            url:url,
            type:'POST',
            dataType:"json",
            data: items,
            success: function (data) {  
                var json = $.parseJSON(data);
                console.log(data);
            },
            error: function (xhr, textStatus, error) {
                $("#form_error").css('padding','7px').css('border-radius','4px').html('Error recieved: ' + error).fadeIn();
                console.log("Status: "+textStatus);
                console.log("Type: "+error);
            }
        });
    }
});
var signin_view = new SigninView({
    el: $("#login_form")
}); 

We are two people working on this, I have taken upon myself to work with Python, while my friend takes care of the js-part. I have yet to experience enough of Django to actually find what might have caused an error to arise due to cookies. I try, most of the time, to stay away from cookies, if I can, but it seems difficult here.

And of course: The traceback:

Traceback:
File "/home/ryuu/Programming/Python/tabr/venv/local/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
  114.                     response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/ryuu/Programming/Python/tabr/venv/local/lib/python2.7/site-packages/django/views/generic/base.py" in view
  69.             return self.dispatch(request, *args, **kwargs)
File "/home/ryuu/Programming/Python/tabr/venv/local/lib/python2.7/site-packages/django/views/generic/base.py" in dispatch
  87.         return handler(request, *args, **kwargs)
File "/home/ryuu/Programming/Python/tabr/venv/local/lib/python2.7/site-packages/django/utils/decorators.py" in _wrapper
  29.             return bound_func(*args, **kwargs)
File "/home/ryuu/Programming/Python/tabr/venv/local/lib/python2.7/site-packages/django/views/decorators/debug.py" in sensitive_post_parameters_wrapper
  75.             return view(request, *args, **kwargs)
File "/home/ryuu/Programming/Python/tabr/venv/local/lib/python2.7/site-packages/django/utils/decorators.py" in bound_func
  25.                 return func(self, *args2, **kwargs2)
File "/home/ryuu/Programming/Python/tabr/venv/local/lib/python2.7/site-packages/django/utils/decorators.py" in _wrapped_view
  95.                     result = middleware.process_view(request, view_func, args, kwargs)
File "/home/ryuu/Programming/Python/tabr/venv/local/lib/python2.7/site-packages/django/middleware/csrf.py" in process_view
  111.                 request.COOKIES[settings.CSRF_COOKIE_NAME])

Exception Type: AttributeError at /login/validate/
Exception Value: 'LoginView' object has no attribute 'COOKIES'
like image 257
Richard Atterfalk Avatar asked Feb 19 '14 12:02

Richard Atterfalk


People also ask

How to use decorators in Django class based views?

To decorate every instance of a class-based view, you need to decorate the class definition itself. To do this you apply the decorator to the dispatch() method of the class. The decorators will process a request in the order they are passed to the decorator.

What is cbv in Django?

A view is a callable which takes a request and returns a response. This can be more than just a function, and Django provides an example of some classes which can be used as views. These allow you to structure your views and reuse code by harnessing inheritance and mixins.

Which method is used to write a cookie in Django?

Django provides built-in methods to set and fetch cookie. The set_cookie() method is used to set a cookie and get() method is used to get the cookie. The request. COOKIES['key'] array can also be used to get cookie values.


1 Answers

You used functions decorators on a method.

This won't work: the function as returned by the decorator expects its first argument to be a request, and receives self instead.

Use:

from django.utils.decorators import method_decorator

csrf_protected_method = method_decorator(csrf_protect)
# and so on

Check the documentation for more details.

like image 91
Thomas Orozco Avatar answered Oct 06 '22 01:10

Thomas Orozco