Django: how to write the name of the current user from each view (django)

I am writing a small social application. One of the features is to write the username in the website header. So, for example, if I logged in and my name is Oleg (username), I should see:

Hello Oleg | Click to edit profile

Otherwise, I should see something like:

Hi, please register or join

I want to show this on every page of my site. The obvious solution is to pass the request.user object to all kinds of my site. But here http://www.willmer.com/kb/category/django/ I read that I can just access the request object from any template by simply including:

TEMPLATE_CONTEXT_PROCESSORS = ( 'django.core.context_processors.request', ) 

I don’t know why, but actually it didn’t work :(

Can someone help me and suggest a solution?

Many thanks,

Oleg

+6
django
source share
6 answers

Also note that you should use django.core.context_processors.auth instead of django.core.context_processors.request, if you do not, the entire request context is needed. Then you can simply enter:

 Hello {{ user.get_full_name }} 

in your template.

Remember to pass context_instance=RequestContext(request) when you call render_to_response (or use direct_to_template ).

+7
source share

There are probably two problems here.

First, if you override TEMPLATE_CONTEXT_PROCESSORS as you did, you will override the default, which is probably not a good idea. By default, this parameter already includes the auth processor, which in any case gives you the user variable. If you definitely need a request , you should do it (pay attention to += ):

 TEMPLATE_CONTEXT_PROCESSORS += ( 'django.core.context_processors.request', ) 

Secondly, as described in the documentation here when using context processors, you need to make sure that you are using RequestContext in your template. If you use render_to_response , you should do it like this:

 return render_to_response('my_template.html', my_data_dictionary, context_instance=RequestContext(request)) 
+6
source share

Use

from django.template import RequestContext

instead

from django.template import Context

So now just call RequestContext (request, context)

More details here .

+1
source share

After you have configured the context process, the request is passed to the template in the form of a variable called request . To access a custom object inside a variable, you need to drill it:

 {{ request.user }} 

The following is a list of attributes stored in the Django Request object . More specifically, here is the attribute.

0
source share
 {% if user.is_authenticated %} <p>Welcome, {{ user.username }}. Thanks for logging in.</p> {% else %} <p>Welcome, new user. Please log in.</p> {% endif %} 

It would be enough if you already have TEMPLATE_CONTEXT_PROCESSORS installed.

0
source share

I think just adding locals() can solve the problem.

 return render_to_response('my_template.html', my_data_dictionary,locals()) 
0
source share

All Articles