Providing current user to all templates in django project
I wonder if there is a way to provide all templates in a django app with a current user variable so that I can control the login and logout functions on all pages. This is a very common practice, so there should be an obvious solution that I missed. I know about the class RequestContext
, but that means I have to add it to all views in the application that seem impractical. Maybe a custom template tag?
source to share
It uses a template context processor: django.core.context_processors.auth
. Review the documentation , you can access the current user and permissions in templates.
source to share
You can use a special tag for this.
Note that, by default, a custom tag does not have access to the object request
and therefore no custom data. To access request
, you can define a custom tag using an attribute takes_context
and grab the request from context:
Something like:
@register.inclusion_tag('userdata.html', takes_context = True)
def userdata(context):
request = context['request']
user = request.user
return {'user':user}
source to share