Problem Description:
I got an invalid Form (form.is_valid() == False) using models.ModelForm class while models.Form class worked. I took several hours trying to figure it out, still don’t get the answer.
The following code works fine.
class UserInfo(models.Model):
user_name = models.CharField(max_length=50, unique=True)
password = models.CharField(max_length=256)
email = models.EmailField(max_length=50, unique=True, blank=True)
time_creation = models.DateTimeField(auto_now_add=True, null=True)
def login(request):
if request.method == 'POST':
form = LoginForm(request.POST)
if form.is_valid():
username = form.cleaned_data.get('user_name')
password = form.cleaned_data.get('password')
try:
user = UserInfo.objects.get(user_name=username)
except :
message = 'User does not exsit'
return render(request, 'manager/login_.html', {'form': form, 'message': message})
if user.password == password:
return redirect("manager/home.html")
else:
message = 'Password is wrong'
return render(request, 'manager/login_.html', {'form': form, 'message': message})
else:
print('form is invalid')
form = LoginForm()
return render(request, 'manager/login.html', {'form': form})
else:
form = LoginForm()
return render(request, 'manager/login_.html', {'form': form})
class LoginForm(forms.Form):
user_name = forms.CharField(
max_length=50,
label='User',
)
password = forms.CharField(
max_length=50,
label='Password',
)
If I change the form using Models.Form as follows, it won’t work:
class LoginForm(forms.ModelForm):
class Meta:
model = UserInfo
fields = ('user_name', 'password')
labels = {
'user_name': "User",
'password': "Password",
}
When I enter an invalid username that doesn’t exist in the database. It prompts ‘User does not exsit’, which shows that it caught the exception. But when I enter a correct username with a valid or invalid password it returns invalid form( I insert a print(‘Invalid form’) in the code)