首页 文章

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

提问于
浏览
1

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

我想要做的是,如果在表单提交后,用户处于非活动状态,则显示不同的错误消息,如果用户未经过身份验证,则显示不正确的用户名密码错误消息 . 这不起作用 . 在这两种情况下,它始终显示"Incorrect username or password!" . 但是在视图中,即使对于非活动用户,user.is_authenticated也会返回 True .

我还有其他的方法来完成这项工作吗?我也试过了

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

但这也不起作用,即使当我尝试打印 form.errors 时,它显示非活动用户的文本"This account is inactive" .

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

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)

2 回答

  • 2

    您的登录模板中没有任何检查 {% if user.is_authenticated %} 的点 . 如果用户已通过身份验证,那么您的 custom_login 视图会将其重定向到主页 .

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

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

    因此,检查 {% if 'inactive' in form.errors %} 将不起作用,因为错误与键 __all__ 一起存储,而不是 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
    
  • 1

    只是为了补充Alasdair的非常明智的答案,如果你想明确检查用户是否存在但是不活动,你可以使用 AuthenticationForm.get_user() ,即:

    {% if form.errors %}
      {% with form.get_user as user %}
        {% if user %}
           {# the user is inactive #} 
        {% else %}
           {# no user matching username/password #} 
        {% endif %}
      {% endwith %}
    {% endif %}
    

    这假设您正在使用默认的 django.contrib.auth.forms.AuthenticationForm 当然 - 您可以使用自己的并覆盖 confirm_login_allowed() 来实现您自己的策略 .

相关问题