4

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 Answers 2

5

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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
That was a really helpful link
2

Context processors.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.