N
N
Nikita Tonkoshkurov2019-07-08 17:09:24
Django
Nikita Tonkoshkurov, 2019-07-08 17:09:24

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)

But when I try to login, every time is_valid returns False, I checked with different accounts, with exactly the correct data
Views.py
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",
    })

What should I do? I would be glad for any help_)

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey Gornostaev, 2019-07-08
@hardrocknyasha

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 question

Ask a Question

731 491 924 answers to any question