almost a beginner almost a beginner - 3 months ago 22
Python Question

Django logout function is not working

I'm using the Django login and logout functions, the login function works, but the logout is not working.

In my HTML file, I have:

<a href="{% url 'django.contrib.auth.views.logout' %}">logout</a>
<a href="{% url 'django.contrib.auth.views.login' %}">login</a>


in my urls.py file I have:

url(r'^$', 'django.contrib.auth.views.login', {
'template_name': 'blog/login.html'
}),

url(r'^$', 'django.contrib.auth.views.logout', {
'template_name': 'blog/logout.html'
}),


When I login, it works perfectly fine, and I can display the logged in person's name. But when I logout, I'm still logged in because the logged in user's name is still displayed in the banner area.

in my HTML file I have:

{% if user.is_authenticated %}
{{ user }}
{% endif %}


If the logout function worked, the user name shouldn't be displayed. So I'm assuming it is not working.

What seems to be the issue, any help/direction would be appreciated.

Thanks in advance,

Answer

There are a couple of issues here.

Firstly, you have exactly the same URL pattern ('^$') for both login and logout views. This means that the second (logout) pattern will never actually be used because the first one always matches. When you try to log out, the first view that matches is the login view, hence you can never log out.

Change it to:

from django.contrib.auth import views as auth_views

url(r'^login/$', auth_views.login, {
    'template_name': 'blog/login.html'
}, name='login'),

url(r'^logout/$', auth_views.logout, {
    'template_name': 'blog/logout.html'
}, name='logout'),

(See the documentation on using the authentication views.)

Then in your template, you need to refer to the URLs using their names (which I have added above):

<a href="{% url 'logout' %}">logout</a>
<a href="{% url 'login' %}">login</a>

Your current approach (of passing a dotted path to a URL function) has been deprecated since Django 1.8 and was removed in Django 1.10, so you should stop using it.