简体   繁体   中英

Django how to override form validation for a required field

I would like to override validation for a password field on my form which is required. Below is what I have tired.

 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

However, I still get the message This field cannot be blank.

PS my reasons for doing this is if NONE my createUser method assigned a random password.

EDIT:

 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'),
        )

mark the field as non-required in the form's constructor:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM