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

2009 January 13

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. So I decided to blog about it and any other gotchas I find along the way in a series entitled, ‘Django Gotchas’.

One Response leave one →
  1. 2009 April 22
    Jeremy Dunck permalink

    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.

Leave a Reply

Note: You can use basic XHTML in your comments. Your email address will never be published.

Subscribe to this comment feed via RSS