对于模板上的非活动用户,user.is_authenticated 始终返回 False

2024-06-19

在我的模板中,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 %}

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

我还有其他方法可以完成这件事吗?我也尝试过

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

但这也不起作用,即使当我尝试打印时form.errors,它为不活动的用户显示文本“此帐户不活动”。

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

视图.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_loginview 会将他们重定向到主页。

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

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

因此检查{% if 'inactive' in form.errors %}不起作用,因为错误是与密钥一起存储的__all__, not inactive.

你可以做{% if 'This account is inactive.' in form.non_field_errors %}但这非常脆弱,如果 Django 更改了非活动用户的错误消息文本,就会崩溃。

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

{{ form.non_field_errors }}

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

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

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

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

class MyAuthenticationForm(AuthenticationForm):
    error_messages = my_error_messages
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

对于模板上的非活动用户,user.is_authenticated 始终返回 False 的相关文章

随机推荐