扩展form.is_valid() [英] Extending form.is_valid()
问题描述
我正在学习Django,偶然发现了需要帮助的地方:
I am learning Django, and i stumbled upon something that I need help with:
forms.py
class UserForm(forms.ModelForm):
password1 = forms.CharField(widget=forms.PasswordInput())
password2 = forms.CharField(widget=forms.PasswordInput())
class Meta:
model = User
fields = ('username', 'email', 'password1','password2')
def password_matched(self):
if self.data['password1'] != self.data['password2']:
self.errors['password'] = 'Passwords do not match'
return False
else:
return True
def is_valid(self):
valid = super(UserForm,self).is_valid()
password_matched = self.password_matched()
if valid and password_matched:
return True
else:
return False
views.py
def register(request):
#blah...
user.set_password(user.password)
# user.set_password(user.password1) doesn't work ! WHY!?
所以基本上,我在检查 pw1 == pw2
,
检查后,我希望将用户密码设置为password1。
我最初使用 user.set_password(user.password1)行
,但是它抱怨User对象没有 password1
,但是当我使用 password $ c $时它就可以工作c>。
So basically, I am checking if pw1 == pw2
,
after checking, I wish to set the user's password to password1.
I initially used the line user.set_password(user.password1)
but it complained that User object doesn't have password1
, yet it worked when I used password
.
为什么?谢谢。
推荐答案
为此,您最好使用 clean
方法,并且永远不要触摸 is_valid
方法。
You should be ideally using the clean
method for this, and never be touching the is_valid
method.
类似这样的事情:
def clean(self):
cd = self.cleaned_data
password1 = cd.get("password1")
password2 = cd.get("password2")
if password1 != password2:
#Or you might want to tie this validation to the password1 field
raise ValidationError("Passwords did not match")
return cd
现在,在视图中
def register(request):
#blah...
form = UserForm(request.POST or None)
if request.method == "POST":
if form.is_valid(): #This would call the clean method for you
user = User.objects.create(...)
user.set_password(form.cleaned_data.get("password1"))
user.save()
else: #Form is invalid
print form.errors #You have the error list here.
这篇关于扩展form.is_valid()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!