开发者

Django field required in a clean method in a form class

开发者 https://www.devze.com 2022-12-09 14:50 出处:网络
I want to redefine the required attribute for a field in a clean method of my form file: class NewUserFullForm(NewUserForm):

I want to redefine the required attribute for a field in a clean method of my form file:

class NewUserFullForm(NewUserForm):

REGEX_PHONE = '^(\+[0-9]{2})[ \.\-]?[0-9][ \.\-]?[0-9]{2}[ \.\-]?[0-9]{2}[ \.\-]?[0-9]{2}[ \.\-]?[0-9]{2}$'

phone = forms.RegexField(REGEX_PHONE, help_text='Ex : +33 1 34 12 52 30')
fax = forms开发者_JS百科.RegexField(REGEX_PHONE, help_text='Ex : +33 1 34 12 52 30',  required=False)
gsm = forms.RegexField(REGEX_PHONE, help_text='Ex : +33 6 34 12 52 30',  required=False)

def clean(self):
   if self.cleaned_data["asso_waldec"] == True:
      self.fields['phone'].required = True

But my clean method doesn't work


Hey! Have you looked at htis document/examples:

Django Validation

Maybe this will clear it up.


One problem is that the clean function has to return the full collection of cleaned data (see docs). Rather than changing the 'required' attribute I believe you should do the check to see if 'phone' is blank and raise a 'ValidationError' describing the problem.

Also since your form inherits from 'NewUserForm' you should call super(NewUserFullForm, self).clean() to ensure that the inherited fields are cleaned as well.

0

精彩评论

暂无评论...
验证码 换一张
取 消