I'm getting this error when I try to log in with a nonvalid user, I want to be redirected to the login page instead.
It highlights the user.save() on muy views.py
views.py
def user_login(request):
if request.method == 'POST':
form = LoginForm(request.POST)
if form.is_valid():
user = authenticate(request, **form.cleaned_data)
user.save()
if user:
login(request, user)
return redirect('home')
else:
return redirect(reverse('login'))
else:
form = LoginForm()
return render(request, 'accountApp/login.html', {'form': form})
forms.py
from django import forms
from django.contrib.auth.forms import UserCreationForm
class LoginForm(forms.Form):
username = forms.CharField(max_length=100)
password = forms.CharField(widget=forms.PasswordInput)
login.html
{% block content %}
<form method="post">
{% csrf_token %}
<h1>Login</h1>
<fieldset style="width: 250px;">
{{ form|crispy }}
</fieldset>
<button type="submit">Log In</button>
</form>
{% endblock %}
CodePudding user response:
authenticate function returns None in case credentials are wrong so check if user is valid or not. change if condition to if user is not None:
i.e. views.py looks like this.
def user_login(request):
if request.method == 'POST':
form = LoginForm(request.POST)
if form.is_valid():
user = authenticate(request, **form.cleaned_data)
# user variable will be None if it is an invalid user
if user is not None:
login(request, user)
return redirect('home')
else:
return redirect(reverse('login'))
else:
form = LoginForm()
return render(request, 'accountApp/login.html', {'form': form})
refer docs: https://docs.djangoproject.com/en/4.1/topics/auth/default/#django.contrib.auth.login