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.
Recommended Posts