Always including the user in the django template context
@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 to use a preprocessor
A: In your settings add
TEMPLATE_CONTEXT_PROCESSORS = (
'myapp.processor_file_name.user',
)
B: In myapp/processor_file_name.py 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 }}
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