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?

+3


source to share


3 answers


It uses a template context processor: django.core.context_processors.auth

. Review the documentation , you can access the current user and permissions in templates.



+3


source


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}

      

0


source


You can just use {{ request.user }}

to display the name of the current user or maybe for example {{ request.user.is_authenticated }}

to find out if he is an anonymous user or not.

0


source







All Articles