views:

196

answers:

2

I have an app that uses flatpages and other constructs that don't take a request object. This causes problems in base.html. Here's a simple example.

If I wanted something like "Welcome {{ request.user.username }}!" at the top of every page, what's the best way to make that happen?

+2  A: 

Context processors.

Daniel Roseman
+3  A: 

Flatpages use RequestContext in rendering templates. Here's a bit more about RequestContext. Suffice to say, you should be able to write a Context Processor to add request.user to the context of every template. Something like this:

def user(request):
    """A context processor that adds the user to template context"""
    return {
        'user': request.user
    }

Which you would then add to your existing TEMPLATE_CONTEXT_PROCESSORS in settings.py:

TEMPLATE_CONTEXT_PROCESSORS = TEMPLATE_CONTEXT_PROCESSORS + (
    'context_processors.user',
)

You just need to make sure all your views bind RequestContext to their templates as well:

return render_to_response('my_template.html',
    my_data_dictionary,
    context_instance=RequestContext(request))

Here's a good read on Context Processors. They're a very helpful feature.

mazelife
You don't need to write a context processor to add `user`, there's one built in and included by default: `django.core.context_processors.auth`
Daniel Roseman
That was a really helpful link
C. Alan Zoppa