扩展form.is_valid()

时间:2015-05-13 23:57:32

标签: django

我正在学习Django,我偶然发现了一些我需要帮助的东西:

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时它就有效。

为什么?感谢。

1 个答案:

答案 0 :(得分:8)

理想情况下,您应该使用clean方法,而不要触及is_valid方法。

这样的事情:

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.