Home > Blockchain >  Username and password are always incorrect in my django AuthenticationForm
Username and password are always incorrect in my django AuthenticationForm

Time:06-27

I'm trying to login user by his username and password, but when i'm trying to check form.is_valid(), it returns False. Errorlist contain error: "Please enter a correct username and password. Note that both fields may be case-sensitive.". When i don't specify my own post it's doesn't work either.

I was looking for typo, but didn't found any. In internet nothing helped me at all. I tried switch form and it's fields, but error was the same.

views.py

from django.views.generic import *
from django.views.generic import *
from django.contrib.auth.forms import AuthenticationForm
from django.contrib.auth import authenticate, login, logout

...
class RegisterView(CreateView):
    form_class = UserRegisterForm
    success_url = reverse_lazy('main:homepage')
    template_name = "accounts/register.html"

    def post(self, request):
        form = self.get_form()
        if form.is_valid():
            user = form.save()
            login(request, user)
            return redirect("main:homepage")
        else:
            print(form.errors)
            return redirect("accounts:register")

class LoginView(FormView):
    form_class = AuthenticationForm
    template_name = "accounts/login.html"

    def post(self, request):
        form = self.get_form()
        if form.is_valid():
            form.clean()
            user = authenticate(
                request, 
                username=form.cleaned_data["username"], 
                password=form.cleaned_data["password"],
            )
            login(request, user)
            return redirect("main:homepage")
        else:
            print(form.errors)
            print(form.cleaned_data)
            
            return redirect("accounts:login")

forms.py

from django import forms
from django.contrib.auth import get_user_model, authenticate, login
from django.contrib.auth.forms import UserCreationForm, AuthenticationForm

class UserRegisterForm(UserCreationForm):
    email = forms.EmailField()

    class Meta:
        model = get_user_model()
        fields = ['username', 'email', 'first_name']


    def save(self):
        self.clean()
        user = self.Meta.model(
            username = self.cleaned_data['username'], 
            email = self.cleaned_data['email'], 
            password = self.cleaned_data['password2'], 
        )
        user.save()
        return user

login.html

<div >
    <form method="POST">
        {% csrf_token %}
        {{ form.as_p }}
        <button type="submit">CONFIRM LOGIN</button>
    </form>
</div>

CodePudding user response:

class UserRegisterForm(UserCreationForm):
    email = forms.EmailField()

    class Meta:
        model = get_user_model()
        fields = ['username', 'email', 'first_name']


    def save(self):
        self.clean()
        user = self.Meta.model(
            username = self.cleaned_data['username'], 
            email = self.cleaned_data['email'], 
        )
        # Set password with method is solution
        user.set_password(self.cleaned_data['password2']) 
        user.save()
        return user

CodePudding user response:

Your code snippets are all correct , but the way of saving the user's password is incorrect in the from via save method , the way you are saving the password , it saves the raw text form of the password to the database , if you want to check , just open your database and check the password fields , they are stored in raw text format ( exapmle : testing123) where as the django saves , retrieves , password using password hashing alogrithm of sha256 until and unless you have not specified it and its hashes to pbkdf2_sha256... this format .

dont save user like this :

user = User(username = username , password = password , email = email)
user.save()

save like this

user = User(username = username , email = email)
user.set_password(password)
user.save()

Update your code snippet :

from django import forms
from django.contrib.auth import get_user_model, authenticate, login
from django.contrib.auth.forms import UserCreationForm, AuthenticationForm

class UserRegisterForm(UserCreationForm):
    email = forms.EmailField()

    class Meta:
        model = get_user_model()
        fields = ['username', 'email', 'first_name']


    def save(self):
        self.clean()
        user = self.Meta.model(
            username = self.cleaned_data['username'], 
            email = self.cleaned_data['email'], 
        )
        user.set_password(self.cleaned_data['password2'])
        user.save()
        return user

This will do the required work.

CodePudding user response:

The reason this does not work is because passwords are hashed, and your UserRegisterForm does not hash the password properly. There is however no need to override the .save(…) method. Django's UserCreationForm [Django-doc] already takes care of this properly, since it is a ModelForm [Django-doc], so:

from django.contrib.auth import get_user_model
from django.contrib.auth.forms import UserCreationForm

class UserRegisterForm(UserCreationForm):
    email = forms.EmailField()

    class Meta:
        model = get_user_model()
        fields = ['username', 'email', 'first_name']
    
    # no override of save
  • Related