简体   繁体   English

Django注销功能不起作用

[英]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.我正在使用 Django 登录和注销功能,登录功能有效,但注销无效。

In my HTML file, I have:在我的 HTML 文件中,我有:

<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:在我的 urls.py 文件中,我有:

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:在我的 HTML 文件中,我有:

{% 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.首先,登录和注销视图的 URL 模式 ( '^$' ) 完全相同。 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):然后在您的模板中,您需要使用它们的名称(我在上面添加的)来引用 URL:

<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.您当前的方法(将虚线路径传递给 URL 函数) 自 Django 1.8 以来已被弃用,并在 Django 1.10 中被删除,因此您应该停止使用它。

Try this:试试这个:

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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