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
print(form.errors)after you initiated the form instance in your view and post it here