Display error message when login fails in Django

Django:1.10

I want to display an error message when login fails with the authentication system provided by Django.

Apparently, you can use Form's add_error.

The Forms API | Django documentation | Django https://docs.djangoproject.com/en/1.10/ref/forms/api/#django.forms.Form.add_error

Prepare a form,

forms.py


from django import forms

class LoginForm(forms.Form):
    username = forms.CharField(label='LOGIN_ID', max_length=30)
    password = forms.CharField(
            label='PASSWORD', max_length=128, widget=forms.PasswordInput())

Add_error to form in view

views.py


from django.contrib.auth import authenticate, login
from django.shortcuts import get_object_or_404, redirect, render

from .forms import LoginForm

def user_login(request):
    form = LoginForm()
    return render(request, 'polls/login.html', {'form': form})

def authentication(request):
    form = LoginForm(request.POST)
    if form.is_valid():
        username = form.cleaned_data['username']
        password = form.cleaned_data['password']
        user = authenticate(username=username, password=password)
        if user is not None:
            if user.is_active:
                login(request, user)
                return redirect('polls:index')
    form.add_error(None, 'LOGIN_The ID or PASSWORD is different.')
    return render(request, 'polls/login.html', {'form': form})

Just make the template show the error message. (Because the first argument of add_error is NONE, it is obtained from non_field_errors)

login.html


・ ・ ・
{% for error in form.non_field_errors %}
    <p>{{ error }}</p>
{% endfor %}
・ ・ ・

It was displayed like this.

無題.png

Recommended Posts

Display error message when login fails in Django
[Django] Error when SlugField is specified in .filter ()
[Django] Display the error message specified by raise ValidationError
When coverage fails with _sqlite3 error
Implementation of login function in Django
[Django] Display message at redirect destination
When you can't call base.html in Django
How to suppress display error in matplotlib
Django ~ Let's display it in the browser ~
[Django] Error encountered when deploying heroku Part 2
[Django] sqlite version error when running python manage.py in aws cloud9 environment
Permission error when reading Django upload files
[Python] What to check when you get a Unicode Decode Error in Django
When I get a chromedriver error in Selenium
In Django, display batch (command) results sequentially in HTML
Pass login user information to view in Django
Implement JWT login functionality in Django REST framework
Error when trying to install psycopg2 in Python
When accessing from Andorid Chrome, Django CSRF validation fails or you can't log in
Models in Django
Error in random.shuffle
Error in Pyinstaller
I want to get an error message in Japanese with django Password Change Form
Error display (unresolved import'hoge') when importing self-made module does not disappear in VS Code
Error in TensorBoard
Forms in Django
When "Message: session not created" occurs in Python + Selenium
I get an error when I put opencv in pyautoGUI
When you get an error in python scraping (requests)
When "ERROR: HTTP is not supported." Is displayed in mpsyt
Explanation of NoReverseMatch error in "python django super introduction"