python - 对于模板上的非事件用户,user.is_authenticated 始终返回 False

标签 python django django-templates django-authentication

在我的模板 login.html 中,我有:

{% if form.errors %}
    {% if user.is_authenticated %}
    <div class="alert alert-warning"><center>Your account doesn't have access to this utility.</center></div>
    {% else %}
    <div class="alert alert-warning"><center>Incorrect username or password!</center></div>
    {% endif %}
{% endif %}

我想做的是,如果在提交表单后,用户处于非事件状态,则显示不同的错误消息,如果用户根本没有经过身份验证,则显示用户名密码错误错误消息。这是行不通的。总是显示“用户名或密码错误!”在这两种情况下。然而,在 View 内,即使对于非事件用户,user.is_authenticated 也会返回 True

我还有其他方法可以完成这个任务吗?我也尝试过

{% if 'inactive' in form.errors %}

但这也不起作用,即使当我尝试打印 form.errors 时,它会为非事件用户显示文本“此帐户处于非事件状态”。

编辑: 对于 View ,我只是在自定义登录 View 中使用 django 的登录 View

views.py:

from django.contrib.auth.views import login, logout
from django.shortcuts import render, redirect

def custom_login(request, **kwargs):
    if request.user.is_authenticated():
        return redirect('/homepage/')
    else:
        return login(request, **kwargs)

最佳答案

没有任何必要检查您的登录模板中的{% if user.is_authenticated %}。如果用户通过身份验证,那么您的 custom_login View 会将他们重定向到主页。

如果帐户处于非事件状态,则表单将无效并且用户将无法登录。表单的错误将如下所示:

{'__all__': [u'This account is inactive.']}

因此检查 {% if 'inactive' in form.errors %} 将不起作用,因为错误是用键 __all__ 存储的,而不是 inactive .

如果“此帐户处于非事件状态”,您可以执行 {%。在 form.non_field_errors %} 中,但这非常脆弱,如果 Django 更改了非事件用户的错误消息文本,就会中断。

最好显示实际的错误,而不是试图找出模板中的错误类型。显示非字段错误的最简单方法是包含:

{{ form.non_field_errors }}

或者,如果您需要更多控制:

{% for error in form.non_field_errors %}
    {{ error }}
{% endfor %}

如果您需要更改非事件用户的错误消息,您可以对身份验证表单进行子类化,然后在登录 View 中使用它。

my_error_messages = AuthenticationForm.error_messages.copy()
my_error_messages['inactive'] = 'My custom message'

class MyAuthenticationForm(AuthenticationForm):
    error_messages = my_error_messages

关于python - 对于模板上的非事件用户,user.is_authenticated 始终返回 False,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39993714/

相关文章:

python - 对 django 应用程序进行单元测试的良好方法/设计

python - 使用 Django 处理上传的文件

django - 在一个用于CI(Bamboo)的容器中运行postgres 9.5和django

python - django if 标签和 ifequal 标签无法正常工作

python - 使用 Boto3 修改给定 EC2 安全组的规则

python - import pymongo 导致 `ImportError: cannot import name BSON` 。你如何修复导入错误?

python - 按钮 Action 在 selenium python 中不起作用

python - 将模型 slug 字段迁移为现有数据库的唯一字段

python - 如何不在 django 中只缓存模板的一段代码

Django 模板遍历元组列表并为它们提供所有按钮