Reputation: 33625
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'),
)
Upvotes: 0
Views: 1248
Reputation: 9359
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
Upvotes: 2