I have a navigation bar that displays “login” and “register” when the user is not signed in. When the user is signed in, the navigation bar will display the user’s name and the number of messages he has in his inbox.
The problem is that the navigation page is present on around 50 pages, so there are around 50 view functions that have to get the user information and send it to the template. If I want to change this later, it will be a pain!
For example, here is an example view:
def index(request):
user = request.user
...
return render_to_response("page.html", {'user': user})
I have to send the info about the user each time to any page with the navigation bar because my navigation bar contains the code:
{% if user %}
...
{% else %}
....
{% endif %}
Is there a cleaner way to do this?
Edit: Also, I have a UserProfile model which I want to send through to the template. Is there a way to do this, too?
The simplest way is to include
django.contrib.auth.context_processors.authto theTEMPLATE_CONTEXT_PROCESSORSconfiguration in yoursettings.py. As described in the docs it wil add auserandpermsvariable in your template context which gives you direct access to the current user.Not that the default configuration for
TEMPLATE_CONTEXT_PROCESSORSis this (in Django 1.3):So the context processor should already be active und you should be able to access the
uservariable in you templates without returning it in the view.In your views, you can simply use the
rendershortcut which will take care of creating the RequestContext instance that is needed: