Question

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',

)
Was it helpful?

Solution

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

OTHER TIPS

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.

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top