Django如何覆盖必填字段的表单验证

时间:2014-06-12 08:58:46

标签: python django

我想覆盖我的表单上的密码字段的验证,这是必需的。以下是我累了。

 def clean(self):
        super(UserRegistrationForm, self).clean()

        password = self.cleaned_data.get("password")

        if password:
            MIN_LENGTH = 6
            if len(password) < MIN_LENGTH:
                raise forms.ValidationError("Password must be at least %d characters long." % MIN_LENGTH)
        else:
            print(self._errors)
            del self._errors['password']


        return self.cleaned_data

但是,我仍然收到消息This field cannot be blank.

PS我这样做的原因是,如果没有我的createUser方法分配了一个随机密码。

编辑:

 def __init__(self, *args, **kwargs):
        super(UserRegistrationForm, self).__init__(*args, **kwargs)



        self.helper = FormHelper()
        self.helper.form_method = 'post'
        # turn off HTML5 validation
        self.helper.attrs = {'novalidate': ''}
        self.helper.form_show_labels =False

        self.helper.layout = Layout(
            HTML('Enter Password'),
            Field('email'),
            Field('password', placeholder="Password", autocomplete='off'),
            Submit('submit', 'Login to your account', css_class='btn btn-primary btn-block'),
        )

1 个答案:

答案 0 :(得分:1)

在表单的构造函数中将该字段标记为非必需字段:

def __init__(self, *args, **kwargs):
    super(MyForm, self,).__init__(*args, **kwargs)
    self.fields['password'].required = False