djangodjango-debug-toolbar

Request.user has no attribute user when used in settings.py


request.user generates a AttributeError: 'WSGIRequest' object has no attribute 'user' error when I try to use it in my settings.py file. Am I doing something wrong?

Settings.py:

def show_toolbar(request):
    if DEBUG:
        return True
    #if not request.is_ajax() and request.user and request.user.UserSettings.debugger:
    #    return True
    return False
DEBUG_TOOLBAR_CONFIG = {
    'SHOW_TOOLBAR_CALLBACK': 'acacia2.settings.show_toolbar',
}

Solution

  • I can't say for sure without seeing your list of middleware, but this is what I suspect is happening:

    Why does it not work

    If your django-debug-toolbar middleware is before the contrib.auth middleware in the list of middleware defined in your MIDDLEWARE setting, then when the request reaches your debug-toolbar middleware it won't have had a user object set on it yet. Hence your error ('WSGIRequest' object has no attribute 'user').

    How to fix it

    Make sure the django-debug-toolbar middleware goes after the auth middleware, e.g:

    MIDDLEWARE = [
        ...
        'django.contrib.auth.middleware.AuthenticationMiddleware',
        ...
        'debug_toolbar.middleware.DebugToolbarMiddleware',
        ...
    
    ]