Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django: How to write current users name from every view (django)

Tags:

django

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

Hello, Oleg | Click to edit profile

Otherwise I should see something like:

Hello Please sign-up or join

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

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

Not sure why but it actually didn't work :(

Maybe someone can help me and suggest a solution?

Thanks a lot,

Oleg

like image 682
Oleg Tarasenko Avatar asked Jun 28 '09 19:06

Oleg Tarasenko


3 Answers

Also note that you should use django.core.context_processors.auth instead of django.core.context_processors.request if you don't need the whole request context. Then you can simply type:

Hello {{ user.get_full_name }}

in your template.

Don't forget to pass context_instance=RequestContext(request) when you call render_to_response (or use direct_to_template).

like image 72
Arnaud Avatar answered Oct 13 '22 17:10

Arnaud


There are probably two issues here.

Firstly, if you redefine TEMPLATE_CONTEXT_PROCESSORS as you have done you will override the default, which is probably not a good idea. By default, the setting already includes the auth processor, which gives you a user variable anyway. If you definitely need the request as well you should do this (notice the +=):

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

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

return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))
like image 6
Daniel Roseman Avatar answered Oct 13 '22 17:10

Daniel Roseman


Use

from django.template import RequestContext

instead of

from django.template import Context

So now just call RequestContext(request, context)

More here.

like image 1
tefozi Avatar answered Oct 13 '22 17:10

tefozi