0

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    
12
  • The AuthenticationForm would authenticate the users directly - or just use the view directly Commented Jul 3, 2022 at 7:49
  • Please add print(form.errors) after you initiated the form instance in your view and post it here Commented Jul 3, 2022 at 8:21
  • @JSRB <ul class="errorlist"><li>__all__<ul class="errorlist nonfield"><li>Please enter a correct username and password. Note that both fields may be case-sensitive.</li></ul></li></ul> Commented Jul 3, 2022 at 8:51
  • well it seems the credentials are wrong, thus the form is invalid.. Commented Jul 3, 2022 at 8:52
  • I think the problem might be in registering user. can you please post registering the user function. Commented Jul 3, 2022 at 9:02

2 Answers 2

0

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

Sign up to request clarification or add additional context in comments.

Comments

0

Try removing the request from the AuthenticationForm(request, data=request.POST). The AuthenticationForm() function doesn't requires two arguments

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.