5

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

)
Abbasov Alexander
  • 1,848
  • 1
  • 18
  • 27
Dmitriy Smirnov
  • 449
  • 4
  • 15

3 Answers3

4

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.

Burhan Khalid
  • 169,990
  • 18
  • 245
  • 284
3

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
Abbasov Alexander
  • 1,848
  • 1
  • 18
  • 27
  • Now I have a new exception: `NoneType' object has no attribute 'has_header'`. However, in my view I have `return self.render_to_response(context)`. What could it be? – Dmitriy Smirnov Jul 03 '13 at 06:51
  • Where you it use, middleware or `views.py`? – Abbasov Alexander Jul 03 '13 at 06:58
  • I'm trying to set the cookie in the middleware. In `views.py` I have a class based view with a TemplateResponseMixin and so the `get` function of the view returns `self.render_to_response(context)`. – Dmitriy Smirnov Jul 03 '13 at 07:00
  • It's already another problem instead this question. But it seems you wrong calling `render_to_response(template_name[, dictionary][, context_instance][, content_type])` – Abbasov Alexander Jul 03 '13 at 07:04
2

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

Community
  • 1
  • 1
CJ4
  • 2,485
  • 3
  • 26
  • 29