Answer the question
In order to leave comments, you need to log in
How to solve problem with Authentication in django?
I wrote a custom login form:
forms.py
class UsersLoginForm(forms.Form):
username = forms.CharField()
password = forms.CharField(widget=forms.PasswordInput)
def __init__(self, *args, **kwargs):
super(UsersLoginForm, self).__init__(*args, **kwargs)
self.fields['username'].widget.attrs.update({
'class': 'form-control form_log-in form_username',
"name": "username"})
self.fields['password'].widget.attrs.update({
'class': 'form-control form_log-in form_password',
"name": "password"})
def clean(self, *args, **keyargs):
username = self.cleaned_data.get("username")
password = self.cleaned_data.get("password")
if username and password:
user = authenticate(username=username, password=password)
if not user:
raise forms.ValidationError("This user does not exists")
if not user.check_password(password):
raise forms.ValidationError("Incorrect Password")
if not user.is_active:
raise forms.ValidationError("User is no longer active")
return super(UsersLoginForm, self).clean(*args, **keyargs)
def login_view(request):
form = UsersLoginForm(request.POST or None)
print(form.is_valid())
print(form.errors)
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("/",{'user':user})
return render(request, "users/log_in.html", {
"form": form,
"title": "Login",
})
Answer the question
In order to leave comments, you need to log in
You need to read the documentation and note that the authentication backend should be handled by the authentication backend , not the form or view.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question