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

时间:2016-10-12 08:17:02

标签: 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 %}

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

我还有其他方法可以完成这项工作吗?我也试过

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

但这也不起作用,即使我尝试打印form.errors时,它会显示文字&#34;此帐户处于无效状态&#34;对于不活跃的用户。

编辑: 对于视图,我只是在自定义登录视图中使用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 个答案:

答案 0 :(得分: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 :(得分: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()来实施自己的政策。

相关问题