django user variables and login forms

I’ve been working on Pub Gateway this afternoon, and I ended up with a slight problem with django’s authentication module. I’d managed to build a working login form which sent the user back to the home page if they entered a valid username and password. The only other thing I wanted was to change the base template to display a link to the login page for users who hadn’t logged in, and a link to the logout page for users who were logged in. I was using the following template code to decide which link to display:

{% if user.is_authenticated %}
<a href="/accounts/logout/">Logout</a>
{% else %}
<a href="/accounts/login/">Login</a>
{% endif %}

However, the template was only showing the logout link if I was on the login page—on all the other pages it was showing ‘login’ instead, even if I’d already logged in. It turns out that the user variable isn’t passed to the template unless you supply what django calls a ‘context processor’, which is added by default to the login view but not on views which I’d created myself. After a bit of searching through the documentation, I had to modify my views like so:

Original view:
return render_to_response('core/about/index.html')

New view:
return render_to_response('core/about/index.html', context_instance=RequestContext(request))

Possibly obvious to anyone who knows django already, but it took me about half an hour of reading through the documentation to figure this out. It seems a bit clumsy to have to do this on every view, and I’m surprised that there’s no obvious way to say ‘do this on every view unless I tell you not to’, but at least everything is working now.