简体   繁体   中英

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,

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.

Try this:

{% if request.user.is_authenticated %}
  Hello {{ request.user.username }}.
{% else %}
  Hello Guest
{% endif %}

还要确保在 INSTALLED_APPS 下的 settings.py 文件中的 Django 默认应用程序之前,您的应用程序设置首先出现,否则您的注销模板不会被呈现,而是会显示 Django 默认注销页面。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM