Django:干净利落的奇怪事情

时间:2016-01-08 19:49:36

标签: python django

所以这真的很奇怪。当我做clean_email时,我收到一个错误,然后为emailConfirm输出“None”。当我做clean_emailConfirm时,它完美无缺。由于某种原因,我得到了不同的结果,即使我唯一要改变的是函数的名称(clean_email到clean_emailConfirm)。有人有任何想法吗?

class SignUpForm(forms.ModelForm):
    fname = forms.CharField(max_length=256, label="", required=True, widget=forms.TextInput(attrs={'class': 'form-control','placeholder': 'First Name','required':True}))
    lname = forms.CharField(max_length=256, label="", required=True, widget=forms.TextInput(attrs={'class': 'form-control','placeholder': 'Last Name','required':True}))
    email = forms.EmailField(max_length=256, label="", required=True, widget=forms.EmailInput(attrs={'class': 'form-control','placeholder': 'Email','required':True}))
    emailConfirm = forms.EmailField(max_length=256, label="", required=True, widget=forms.EmailInput(attrs={'class': 'form-control','placeholder': 'Email','required':True}))
    password = forms.CharField(max_length=256, label="", required=True, widget=forms.PasswordInput(attrs={'class': 'form-control','placeholder': 'Password','required':True}))
    datetime = forms.DateTimeInput()

    class Meta:
        model=SignUp
        fields=['fname','lname','email','emailConfirm','password']

    # def clean_email(self):    
    #   email=self.cleaned_data.get('email')
    #   emailConfirm=self.cleaned_data.get('emailConfirm')
    #   if email != emailConfirm:
    #       #print(cleaned_data2)
    #       print(email)
    #       print(emailConfirm)
    #       raise forms.ValidationError("Your two emails must be the same!")
    #   else:
    #       return email
    def clean_emailConfirm(self):   
        email=self.cleaned_data.get('email')
        emailConfirm=self.cleaned_data.get('emailConfirm')
        if emailConfirm != email:
            #print(cleaned_data2)
            print(email)
            print(emailConfirm)
            raise forms.ValidationError("Your two emails must be the same!")
        else:
            print(emailConfirm)
            print(email)
            return email

1 个答案:

答案 0 :(得分:4)

您无法通过clean_foo方法交叉验证字段,因为并非所有字段都是'当您在其中一个方法中时,会调用clean_foo个方法,因此可能存在一些尚未填充的表单值。它应该在clean方法中完成。 Django doc非常明确地记录了这一点:

  

当调用表单的clean()方法时,所有个体   将运行字段清理方法(前两节),所以   self.cleaned_data将填充任何幸存下来的数据   远。所以你还需要记住允许的事实   您想要验证的字段可能无法在初始阶段幸存   个别实地考察。