tags:

views:

249

answers:

4

Hi!

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

A: 

Once you have set up the context process, the request is passed to the template as a variable named request. To access the user object within the variable you need to drill into it:

{{ request.user }}

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

Soviut
+1  A: 

Use

from django.template import RequestContext

instead of

from django.template import Context

So now just call RequestContext(request, context)

More here.

zdmytriv
+3  A: 

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).

Arnaud
Just a small note: generic views already have context_instance set, and therefore the {{ user }} variable is already available.
Roberto Liffredo
+3  A: 

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))
Daniel Roseman