tags:

views:

113

answers:

2

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 %}

A: 

If you are using django.contrib.auth and both django.core.context_processors.auth and django.core.context_processors.request are in your TEMPLATE_CONTEXT_PROCESSORS, you can simply use:

{% if request.user.is_authenticated %}
    You're logged in.
{% else %}
    You're not logged in.
{% endif %}
Jack M.
-1 `request.user` is always present, as an unauthenticated user (every user) is a user too.
Marcus Whybrow
You're correct. I am used to checking specific permissions instead of if they're authenticated, so I forgot to chuck that bit in there. I fixed it up.
Jack M.
+4  A: 

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 called user into 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:

{% if user.is_authenticated %}
    You're logged in.
{% else %}
    You're not logged in.
{% endif %}

The problem with using the code that Jack gave, is that the user variable always exists - so that will always evaluate to True (so long as you are using the django.core.context_processors.request context processor, which is not enabled by default). Therefore, to find out if the user is actually logged in, you must use the is_authenticated() method.

Rob Golding