我试图比较密码和确认密码。如果我输入其他密码,它不会引发错误并重定向到登录页面。
models.py
class reg1(models.Model):
name=models.CharField(max_length=100)
city=models.CharField(max_length=100)
email=models.CharField(max_length=100)
username=models.CharField(max_length=100)
password=models.CharField(max_length=100)
cpassword=models.CharField(max_length=100)
class Meta:
db_table='reg1'
forms.py
class regform(forms.Form):
name = forms.CharField(max_length=100)
city = forms.CharField(max_length=100)
email = forms.CharField(max_length=100)
username = forms.CharField(max_length=100)
password = forms.CharField(max_length=100)
cpassword=forms.CharField(max_length=100)
def clean_password(self):
if self.data['password'] != self.data['cpassword']:
raise forms.Error('Passwords are not the same')
return self.data['password']
views.py
if myregform.is_valid():
name1 = myregform.cleaned_data['name']
city1 = myregform.cleaned_data['city']
email = myregform.cleaned_data['email']
username1 = myregform.cleaned_data['username']
password1 = myregform.cleaned_data['password']
password2=myregform.cleaned_data['cpassword']
a=reg1(name=name1,city=city1,email=email,
username=username1,password=password1,cpassword=password2)
a.save()
我希望输出,因为我输入了不同的密码,它将显示密码不匹配的错误
我正在使用带有sqlite3数据库的pycharm软件和django框架。
答案 0 :(得分:0)
clean()
来验证与其他字段相关的数据。ValidationErrors
。class reg1(models.Model):
name = models.CharField(max_length=100)
city = models.CharField(max_length=100)
email = models.CharField(max_length=100)
username = models.CharField(max_length=100)
password = models.CharField(max_length=100)
cpassword = models.CharField(max_length=100)
class Meta:
db_table = "reg1"
class regform(forms.ModelForm):
class Meta:
model = reg1
exclude = ()
def clean(self, cleaned_data):
if cleaned_data["password"] != cleaned_data["cpassword"]:
raise forms.ValidationError("Passwords are not the same")
return cleaned_data
# ...
if myregform.is_valid():
a = myregform.save()