Always including the user in the django template context


I am working on a small intranet site for a small company, where user should be able to post. I have imagined a very simple authentication mechanism where people just enter their email address, and gets sent a unique login url, that sets a cookie that will always identify them for future requests.

In my template setup, I have base.html, and the other pages extend this. I want to show logged in or register button in the base.html, but how can I ensure that the necessary variables are always a part of the context? It seems that each view just sets up the context as they like, and there is no global context population. Is there a way of doing this without including the user in each context creation?

Or will I have to make my own custom shortcuts to setup the context properly?

9/3/2008 12:22:44 PM

Accepted Answer

In a more general sense of not having to explicitly set variables in each view, it sounds like you want to look at writing your own context processor.

From the docs:

A context processor has a very simple interface: It's just a Python function that takes one argument, an HttpRequest object, and returns a dictionary that gets added to the template context. Each context processor must return a dictionary.

9/3/2008 12:31:58 PM

There is no need to write a context processor for the user object if you already have the "django.core.context_processors.auth" in TEMPLATE_CONTEXT_PROCESSORS and if you're using RequestContext in your views.

if you are using django 1.4 or latest the module has been moved to django.contrib.auth.context_processors.auth

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow