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
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).
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))
Use
from django.template import RequestContext
instead of
from django.template import Context
So now just call RequestContext(request, context)
More here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With