django - 在 Django 中,当登录 URL 以 ?next=/accounts/logout/结尾时停止重定向回注销

标签 django django-templates django-authentication

在我的模板中,我当前使用 next 参数将用户重定向回登录页面之前的页面:

<a href="{% url auth_login %}?next={% firstof request.path '/' %}">Log in</a>

firstof 标记确保在 request.path 无效的情况下,它将重定向回根 URL。

这在除注销页面之外的每个页面上都适用。如果我想切换用户,那么我会先注销,然后单击登录。但是我的网址将是

http://127.0.0.1:8000/accounts/login/?next=/accounts/logout/

因此,一旦我登录,我就会立即再次退出。如何使用类似伪代码的内容修改模板:

if request.path and request.path != reverse( 'auth_logout' )
    return request.path

return "/"

最佳答案

我能想到的最简单的解决方案是在您的注销网址中添加 "?next=/" ,这样,一旦用户注销,他将立即重定向到指定的url,因此没有人会在注销时停留在注销页面。

否则,您将必须重写登录 View 并添加所需的任何自定义逻辑,如果 contrib.auth View 是类 View ,这会更容易,但不幸的是,它们目前不是类 View 。

所以复制粘贴它并修改:)(我知道复制粘贴不好,但这是您可以向其添加自定义行为的唯一方法)。

该 View 位于此处: https://code.djangoproject.com/browser/django/trunk/django/contrib/auth/views.py#L25

关于django - 在 Django 中,当登录 URL 以 ?next=/accounts/logout/结尾时停止重定向回注销,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9936763/

相关文章:

python - Django 模板剥离空格?

python - Django - 读取当前的用户认证后端类

android - 如何在我的 Android 应用程序中使用 django 身份验证(django.contrib.auth)

django - 对象不能用 Django 的分页迭代

使用 get_queryset 的 Django ListView 分页

django - 上下文处理器与模板标签的最佳实践?

python - "Unsupported hash type"错误 w/Python 2.6.5 和 django 框架

python - 使用 MIMEApplication 将 s3 文件附加到 smtplib lib 电子邮件

python - 如何在本地运行 OpenShift Django 项目?