Search code examples
djangoformsrequired-field

Django field required in a clean method in a form class


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.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


Solution

  • Hey! Have you looked at htis document/examples:

    Django Validation

    Maybe this will clear it up.