Including user statistics for multiple views

I have a navigation bar that displays "login" and "register" when the user is not logged in. When the user is logged in, the user name and the number of messages that he has in his inbox will be displayed on the navigation bar.

The problem is that the navigation page is present on about 50 pages, so there are about 50 viewing functions that should receive information about the user and send it to the template. If I want to change this later, it will be a pain!

For example, here is an example:

def index(request): user = request.user ... return render_to_response("page.html", {'user': user}) 

Every time I need to send user information to any page using the navigation bar, because my navigation bar contains the code:

 {% if user %} ... {% else %} .... {% endif %} 

Is there a cleaner way to do this?

Edit: In addition, I have a UserProfile model that I want to send to the template. Is there any way to do this too?

+4
source share
4 answers

The easiest way is to include django.contrib.auth.context_processors.auth in the TEMPLATE_CONTEXT_PROCESSORS configuration in settings.py . As described in the docs , add the user and perms to the context of your template, which will give you direct access to the current user.

Not that the default configuration for TEMPLATE_CONTEXT_PROCESSORS is (in Django 1.3):

 ("django.contrib.auth.context_processors.auth", "django.core.context_processors.debug", "django.core.context_processors.i18n", "django.core.context_processors.media", "django.core.context_processors.static", "django.contrib.messages.context_processors.messages") 

So, the context processor must be active, and you must have access to the user variable in your templates without returning it to the view.

In your views, you can simply use the render shortcut, which will take care of creating the required instance of RequestContext:

 from django.shortcuts import render def my_view(request): return render(request, 'template.html' ) 
+2
source

You can create your own template tag, as suggested by DrTyrsa, or create a context processor .

+2
source

To do this, you need a custom template tag .

0
source

Why you need to send the user in all kinds, HttpRequest contains the user, you can easily get it in the template when registering at.

and another solution, save the user in sessions and get access to him in any view or template.

0
source

Source: https://habr.com/ru/post/1388429/


All Articles