Django表示不调用clean_ <fieldname> </fieldname>

时间:2009-12-09 05:21:20

标签: django django-forms

我正在尝试验证表单(以前用过它)。出于某种原因,我似乎无法在调用form.is_valid()时调用各种清理函数,例如clean_username(self)。

我知道目前还没有足够的支票(他们正在建设你看;-)),但这是我的课程:

  class LoginForm(forms.Form):
    username = forms.CharField(max_length=30)
    password = forms.CharField(max_length=30,widget=forms.PasswordInput)

    def clean_password(self):
        print "Cleaning password"
        password = self.cleaned_data['password']
        if password == u"":
            raise forms.ValidationError("Password is blank.")
        return password

    def clean_username(self):
        username = self.cleaned_data['username']
        if len(username) < 4:
            raise forms.ValidationError("Username is fewer than four charecters.")
        return username


class RegistrationForm( LoginForm ):
        confirm_password = forms.CharField(widget=forms.PasswordInput, max_length=30)
        email = forms.EmailField()

        def clean_confirm_password(self):
            print "Cleaning confirm password"
            clean_confirm_password = self.cleaned_data['confirm_password']
            if clean_confirm_password == u"":
                raise forms.ValidationError("Confirming password is blank.")
            return clean_confirm_password

        def clean(self):
            print "Running clean on a registration form"
            print self.cleaned_data.items()
            password = self.cleaned_data['password']
            confirm = self.cleaned_data['confirm_password']
            if password != confirm:
                raise forms.ValidationError('Passwords do not match.')
            return self.cleaned_data

谢谢!

2 个答案:

答案 0 :(得分:25)

在深入了解Django forms.py来源后,我发现了错误的来源。

似乎如果一个字段留空,表单在调用field.clean()之后会为该字段引发ValidationError,但它不会调用clean_<fieldname>,但它仍然调用主要的干净方法班级。为了处理使用这些空白字段的干净方法,您必须执行以下操作:

def clean(self):
    try:
        password = self.cleaned_data['password']
        # etc
    except KeyError:
        raise ValidationError('The password field was blank.')

    return self.cleaned_data

答案 1 :(得分:7)

您可以在字段构造函数中使用required=False来覆盖它。

username = forms.CharField(max_length=30, required=False)
password = forms.CharField(max_length=30,widget=forms.PasswordInput, required=False)

这对您的示例来说似乎不合逻辑,但如果有其他实例

则会很有用