Search code examples
djangodjango-authenticationdjango-registration

Always send the User information in every Django template


I used a pre-built example templates for Django registration and I noticed that for those pages, Django understands user and I do things like user.is_authenticated and user.username.

I tried looking at the views.py code in both Django registration and the django.contrib.auth.views, but I couldn't figure out how those two always sent the user information to the templates.

I could could always explicitly send the user Context information to every view, but that would be violating the DRY principle.

I tried using this solution, but I get an error saying

Put 'django.contrib.auth.context_processors.auth' in your TEMPLATE_CONTEXT_PROCESSORS setting in order to use the admin application.

And even if I placed the above path inside settings.py like this

TEMPLATE_CONTEXT_PROCESSORS = (
    'django.contrib.auth.context_processors.auth',
    'doors.processor_file_name.user',
)

my templates still doesn't know about user.


Solution

  • It turns out that every time I was using render_to_response in my views.py...

    def order_all( request ) :
        orders = Order.objects.all()
        return render_to_response( 'doors/order/list.html', { 'orders' : orders } )
    

    the dictionary isn't a RequestContext. Using a RequestContext will automatically include the TEMPLATE_CONTEXT_PROCESSORS, which in my case will include django.contrib.auth.context_processors.auth, which will pass along the user information to the every template.

    So in other words, I just need to change the code above to this

    def order_all( request ) :
        orders = Order.objects.all()
        return render_to_response( 'doors/order/list.html', context_instance = RequestContext( request, { 'orders' : orders } ) )
    

    Don't forget to import RequestContext too

    from django.template import RequestContext
    

    It also turns out I don't need to explicity include django.contrib.auth.context_processors.auth (or write my custom doors.processor_file_name.user) in the TEMPLATE_CONTEXT_PROCESSORS because django.contrib.auth.context_processors.auth is included by default