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?


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

By : Daniel

The hints are in every answer, but once again, from "scratch", for newbies:

authentication data is in templates (almost) by default -- with a small trick:


from django.template import RequestContext
def index(request):
    return render_to_response('index.html', 
                              {'var': 'value'},

in index.html:

Hi, {{ user.username }}
var: {{ value }}

From here:

This template context variable is not available if a RequestContext is not being used.

By : iutinvg

its possible by default, by doing the following steps, ensure you have added the context 'django.contrib.auth.context_processors.auth' in your settings. By default its added in, so its looks like this


And you can access user object like this,

{% if user.is_authenticated %}
<p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}

For more information, refer here

This video can help you solving your question :)
By: admin