User.is_authenticated Always Returns False For Inactive Users On Template
Solution 1:
There isn't any point checking {% if user.is_authenticated %}
in your login template. If the user is authenticated, then your custom_login
view would have redirected them to the homepage.
If the account is inactive, then the form will be invalid and the user will not be logged in. The forms's errors will look like:
{'__all__': [u'This account is inactive.']}
Therefore checking {% if 'inactive' in form.errors %}
will not work, because the error is stored with the key __all__
, not inactive
.
You could do {% if 'This account is inactive.' in form.non_field_errors %}
but this is very fragile, and would break if Django ever changed the text of the error message for inactive users.
It would be better to display the actual errors, rather than trying to find out what sort of error it is in the template. The easiest way to display non-field errors is to include:
{{ form.non_field_errors }}
Or, if you need more control:
{% forerror in form.non_field_errors %}
{{ error }}
{% endfor %}
If you need to change the error message for inactive users, you can subclass the authentication form, then use that in your login view.
my_error_messages = AuthenticationForm.error_messages.copy()
my_error_messages['inactive'] = 'My custom message'
class MyAuthenticationForm(AuthenticationForm):
error_messages = my_error_messages
Solution 2:
Just to complement Alasdair's very sensible answer, if you really want to explicitely check whether the user exists but is inactive, you can use AuthenticationForm.get_user()
, ie:
{% if form.errors %}
{% with form.get_user as user %}
{% if user %}
{# the user is inactive #}
{% else %}
{# no user matching username/password #}
{% endif %}
{% endwith %}
{% endif %}
This is assuming you're using the default django.contrib.auth.forms.AuthenticationForm
of course - you can use your own and override the confirm_login_allowed()
to implement your own policy.
Post a Comment for "User.is_authenticated Always Returns False For Inactive Users On Template"