I am trying to make a Django login screen that shows the errors when the user for example doesn't type the right password. But the only error i am receiving is the "This user doesn't exist!" how can i make the other error messages to show up? What is the problem with my code?
forms.py
class UserLogInForm(forms.Form):
username = forms.CharField()
password = forms.CharField(widget=forms.PasswordInput)
def clean(self, *args, **kwargs):
username = self.cleaned_data.get("username")
password = self.cleaned_data.get("password")
#if username and password:
# user = get_user_model()
user = authenticate(username=username, password= password)
# user = authenticate(username=username)
if not user:
raise forms.ValidationError("This user does not exist!")
if not user.check_password(password):
raise forms.ValidationError("Incorrect password!")
if not user.is_active:
raise forms.ValidationError("This user is no longer active.")
return super(UserLogInForm, self).clean(*args, **kwargs)
views.py
def login_view(request):
title = "Login"
form = UserLogInForm(request.POST or None)
if form.is_valid():
username = form.cleaned_data.get("username")
password = form.cleaned_data.get("password")
user = authenticate(username=username, password=password)
login(request, user)
return redirect('/')
return render(request, "form.html", {"form": form, "title": title, 'errors': form.non_field_errors()})
form.html
<form method='POST' action='' enctype="multipart/form-data">{% csrf_token %}
{{ form.non_field_errors }}
<table align="center">
<tr>
<td>{{ form.username.label_tag }}</td>
<td>{{ form.username }}</td>
</tr>
<tr>
<td>{{ form.password.label_tag }}</td>
<td>{{ form.password }}</td>
</tr>
</table>
<div id="wrapper">
<button id="button" type="submit">Login</button>
</div>
</form>
userwill becomeNone. If you want to raise more specific errors, raise them inauthenticate().