This is more theory question than specific code problem.
I'm kinda confused how information like username, user email, etc. is stored and accessed in Django.
From what I know:
I can access it like {{user.username}}
IF previously I got here by using render()
or render_to_response()
with RequestContext inside. If I got on the page by using HttpResponseRedirect
than I don't have access to user.username
and it is just blank here.
What I want to know:
Is there way to access user data from every single page regardless of how I got there? I mean even if I don't use any views at all, like manually typing address.
Strangely enough, I always thought that data like username is accessible through sessions, but 9 out of 10 articles about this topic always talk about RequestContext and other stuff that passes values from one page to another.
I also read about custom context processors, but as I think it is only good for specific purposes, not simple username.
So maybe in a nutshell the question is:
If I want to display for example username in the corner of every single page of the site - how should I do that?
What happens here (for dummies)
HttpResponseRedirect doesn't affect anything at all. The problem is that it is redirecting to render_to_response() call that does not include RequestContext. If we do not specify RequestContext it will write it out as blank and force it over the session data given by the context_processor.auth, so you basically have nothing at all as your context data at this page.
How it should be done(in my opinion) is that you always use render() or render_to_response() with RequestContext in any of your views, don't forget it. And don't worry at all about various redirects since they do not affect context data. Static html pages get context data from processor, it works, my fault I didn't check it twice beforehand.
Just output the {{ user.username }}
. If user is logged, some of auth middleware and django.contrib.auth.context_processors.auth
context processor are enabled then the username will be shown.
The middleware takes the user id from the session, loads the User
from the db and sets the request.user
attribute. Then context processor takes the request.user
attribute and injects it into the RequestContext as the user
variable.
To make the user
variable available in your template you should use the render()
shortcut. Or the render_to_response()
with the RequestContext
as the context_instance
argument.