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?

+2  A: 

If you can hook your authentication into the Django authentication scheme you'll be able to use request.user.

I think this should just be a case of calling authenticate() and login() based on the contents of your Cookie.

Edit: @Staale - I always use the locals() trick for my context so all my templates can see request and so request.user. If you're not then I guess it wouldn't be so straightforward.

Dave Webb
+13  A: 

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.

Ryan Duffield
+1  A: 

@Dave To use {{user.username}} in my templates, I will then have to use requestcontext rather than just a normal map/hash:

So I guess there are no globals that the template engine checks.

But the RequestContext has some prepopulate classes that I can look into to solve my problems. Thanks.

+13  A: 

@Ryan: Documentation about preprocessors is a bit small

@Staale: Adding user to the Context every time one is calling the template in view, DRY

Solution is very simple

A: In your settings add


B: In myapp/ insert

def user(request):
    if hasattr(request, 'user'):
        return {'user':request.user }
    return {}

From now on you're able to use user object functionalities in your templates.

{{ user.get_full_name }}
+3  A: 

There is no need to write a context processor for the user object if you already have the "django.core.context_processors.auth" initialized.

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