Skip to content
Jan 13 / Nizam Sayeed

Django Gotcha: Never set a variable called ‘user’ in your RequestContext

Okay. So I was working on some view code in a Django project and I noticed something weird. The view started rendering as if the user was no longer logged in. Odd thing was that it was only doing that for that one view. I banged my head for a while and then I realized that I had populated a variable called ‘user’ in the RequestContext for render_to_response. E.g.,

def my_view(request):
    ...
    user_obj = User.objects.get(id = user_id)
    data = { 'user': user_obj }
    ...
    return render_to_response(template, data, context_instance = RequestContext(request))

This caused the default user object that gets set in the request context by django.core.context_processors.auth to be overridden. So stuff like user.is_authenticated stopped working in the templates.

This was my first major Django gotcha.

  • Jeremy Dunck

    May you have few gotchas.

    FWIW, this actually can happen with any variable– context is a stack of dictionaries, with any keys in the topmost dictionary shadowing any keys further in the stack. Context processor values are inherently near the bottom of the stack, and {{ user }} is typically available from the auth context processor.