1

I have the following middleware function:

class LastVisitMiddleware(object):
    def process_response(self, request, response):
        if request.user.is_authenticated():
            customer = get_customer(request)
            Customer.objects.filter(pk=customer.pk).update(last_visit=now())
        return response

My middleware entries look like this:

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

)

My url looks like:

url(r'^dashboard/$', views.dashboard, name='dashboard'),

When I go to urls that have a forward slash the page loads normally. When I omit the forward slash I get the error:

WSGIRequest object has no attribute user

When I remove the middleware I have no issues whether I use the forward slash or not.

How can I prevent from throwing this error with or without a forward slash?

Atma
  • 29,141
  • 56
  • 198
  • 299

2 Answers2

4

I know that Django redirects any urls without the trailing /, so /home to /home/, but I am not sure when Django does this redirection (apparently after it has run the middleware?). One way to get around this is to check if the user object has been set;

if hasattr(request, 'user') and request.user.is_authenticated():

This should fix your problem.

vishen
  • 459
  • 2
  • 7
  • It looks like you're correct; the redirection will happen before the AuthenticationMiddleware is run, by default. I was just encountering the same issue when running a request without a trailing slash, and adding the trailing slash fixed it. Thank you! – Joey Wilhelm Jul 14 '15 at 21:14
0

During the response phases (process_response() and process_exception() middleware), the classes are applied in reverse order, from the bottom up

similar question:

Django: WSGIRequest' object has no attribute 'user' on some pages?

Community
  • 1
  • 1
James Lin
  • 25,028
  • 36
  • 133
  • 233