Home > Mobile >  Why AuthenticationForm() in Django is not being valid?
Why AuthenticationForm() in Django is not being valid?

Time:07-06

So I've been trying to create a function in Django for users to log into their accounts. But it is only working for super users. When I try to log in from other accounts, it keeps resetting the password and gives error message 'Please enter a correct username and password'. However, both username and password are correct.

Data from request.POST is coming as a QuerySet (keys-'csrfmiddlewaretoken','username','password'). When I put request.POST into AuthenticationForm(), it is not going through 'if form.is_valid():' part.

What should I do to make this work? Please, can someone help me? Thanks in advance.

Here is the code:

def log_in(request):
    form=AuthenticationForm()
    if request.method=="POST":
        form=AuthenticationForm(request, data=request.POST)
        if form.is_valid():
            username=form.cleaned_data.get('username')
            password=form.cleaned_data.get('password')
            user=authenticate(username=username,password=password)
            if user is not None:
                login(request,user)
                messages.info(request,'You have successfully logged in!')
                return redirect('news')
            else:
                messages.error(request,'Invalid data!') 
        else:
            messages.error(request,'Invalid data!')           
    return render(request,'post/login.html',{'form':form})





def register_user(request):
    form=UserCreateForm
    if request.method=='POST':
        form=UserCreateForm(request.POST)
        if form.is_valid():
            user=form.save()
            login(request,user)
            messages.success(request,'Registration was successfull')
            return redirect('news')
        messages.error(request,'Try again!')   
    return render(request,'post/register.html',{'form':form})





class UserCreateForm(UserCreationForm):
    email=forms.EmailField(required=True)

    class Meta:
        model=User
        fields=['username','email','password1','password2']

    def save(self,commit=True):
        user=super(UserCreationForm, self).save(commit=False)
        user.email=self.cleaned_data.get('email')
        if commit:
            user.save()
        return user    

CodePudding user response:

with following code (django 4.0.6), i was able to get a user logged in:

def log_in(request):
    form = AuthenticationForm()
    if request.method == "POST":
        form = AuthenticationForm(None, data=request.POST)
        if form.is_valid():
            form.clean()
            user = form.get_user()
            if user is not None:
                login(request, user)
            else:
                print("nay")
        else:
            print("ney")
    return render(request, 'login.html', {'form': form})

your login method should be look like this:

def log_in(request):
    form = AuthenticationForm()
    if request.method == "POST":
        form = AuthenticationForm(None, data=request.POST)
        if form.is_valid():
            form.clean()
            user = form.get_user()
            if user is not None:
                login(request,user)
                messages.info(request,'You have successfully logged in!')
                return redirect('news')
            else:
                messages.error(request,'Invalid data!') 
        else:
            messages.error(request,'Invalid data!')           
    return render(request,'post/login.html',{'form':form})

the AuthenticationForm already performs authenticate in its clean step - so you don't have to do that. Just call clean and after that the get_user function

PS: Keep in mind, your user must be active -> user.is_active must be True

CodePudding user response:

In some cases, the similarity of the class names can be the reason for this and it confuses us. This is where an error occurred during inheritance. You should write the UserCreateForm class and the problem is solved.

  • Related