开发者

Writing better code for session variable check from render_to_response

开发者 https://www.devze.com 2022-12-20 13:42 出处:网络
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.\"?

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(开发者_如何学Pythonrequest)
    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 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.


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

精彩评论

暂无评论...
验证码 换一张
取 消