How to add Login/Logout link (Django)

Go To StackoverFlow.com

1

I need a link in django template which turns into logout if user is authenticated. (i have already implemented login/logout pages)

tried {% if user.is_authenticated %} {% endif %} and {% if user.is_anonymous %} {% endif %} but didn't work.

Test Code (https://docs.djangoproject.com/en/dev/topics/auth/) -

{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}

Returns false evan after logged in successfully.

2012-04-04 02:45
by ChamingaD
Use {% else %} as well - Blender 2012-04-04 02:51
@Blender yes, tried using with that also - ChamingaD 2012-04-04 02:54
Then you're coding something wrong. Post your template code - Blender 2012-04-04 02:54
@Blender posted : - ChamingaD 2012-04-04 02:55
That should work. Is user.is_authenticated set correctly, or is it always True - Blender 2012-04-04 02:56
@Blender that's test code i taken from https://docs.djangoproject.com/en/dev/topics/auth/ (not for login/logout - ChamingaD 2012-04-04 02:56
@Blender what you mean by set correctly ? {% if user.is_authenticated %} always returns false - ChamingaD 2012-04-04 02:58
use request.user; furthermore, according your post question http://stackoverflow.com/questions/9989149/redirect-back-to-previous-page-after-logged-in-django , you may not login correctl - okm 2012-04-04 03:29
@okm no, login works fine. do i have to add anything to settings to make {% if user.is_authenticated %} work - ChamingaD 2012-04-04 03:41


4

It doesn't look like there is anything wrong with the template code you posted. So I'd check out the associated view. In particular, if you're using a custom-made view (rather than, say, a generic view), remember to supply a RequestContext to your template.

From the Django tutorial, part 4:

from django.template import RequestContext
# ...
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p},
                           context_instance=RequestContext(request))
2012-04-04 03:39
by jreyes
Thanks :) It worked by adding context_instance=RequestContext(request)ChamingaD 2012-04-04 03:49
You can also use the <code>render</code> shortcutBurhan Khalid 2012-04-04 04:23
Ads