Is this the most efficient and clean way to check the sessions for a username variable and output (depending on whether or not it is there) either “You are logged in.” or “You are logged out.”?
PYTHON (DJANGO)
def logged_in(request)
return render_to_response('loggedincheck.html', {'request': request.session.get['username']})
HTML
{% if request %}
You’re logged in. {% else %}
You’re not logged in. {% endif %}
Django comes with some template context processors – which are simply functions that insert variables into every template that is rendered on your site.
As @Jack states, one of these is called
django.core.context_processors.auth. This inserts a variable calleduserinto every template, and is enabled by default.Therefore, to find out if a user is logged in or not, you should use this code in your templates:
The problem with using the code that Jack gave, is that the
uservariable always exists – so that will always evaluate toTrue(so long as you are using thedjango.core.context_processors.requestcontext processor, which is not enabled by default). Therefore, to find out if the user is actually logged in, you must use theis_authenticated()method.