Dmitriy Smirnov
Dmitriy Smirnov

Reputation: 449

Django 'WSGIRequest' object has no attribute 'set_cookie'

I keep on getting this exception when I do request.set_cookie() in the process_view of a custom middleware class. Here is the order of middleware classes in my settings.py:

MIDDLEWARE_CLASSES = (
    'django.contrib.sessions.middleware.SessionMiddleware',
    'website.middleware.UserLastActiveMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',

)

Upvotes: 5

Views: 7550

Answers (3)

Burhan Khalid
Burhan Khalid

Reputation: 174662

To start off with, set_cookie() is a method of HttpResponse, not HttpRequest, as you set cookies in your response to a requests.

Secondly, your middleware should come after AuthenticationMiddleware, since presumably it has to do with users.

Upvotes: 4

CJ4
CJ4

Reputation: 2535

You can take a look at this question: Django: WSGIRequest' object has no attribute 'user' on some pages?

This problem usually occurs when you do not add the trailing slash because then a redirect is done to the url containing a trailing slash

Upvotes: 2

Abbasov Alexander
Abbasov Alexander

Reputation: 1938

You should set_cookie() call from response object. Example:

def process_response(self, request, response):
    ...
    response.set_cookie('user_agreement', user_agreement, domain='.mysite.com')
    return response

Upvotes: 3

Related Questions