Django: Make certain fields in a ModelForm required=False
following from comments. Probably yes:
class ThatForm(ModelForm): def __init__(self, *args, **kwargs): # first call parent's constructor super(ThatForm, self).__init__(*args, **kwargs) # there's a `fields` property now self.fields['desired_field_name'].required = False
you ought to add blank=True
to the corresponding model
If the model field has blank=True, then required is set to False on the form field. Otherwise, required=True.
Also see the documentation for blank itself.
When we need to set required option on a bunch of fields we can:
class ThatForm(forms.ModelForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) for field in self.Meta.required: self.fields[field].required = True class Meta: model = User fields = ( 'email', 'first_name', 'last_name', 'address', 'postcode', 'city', 'state', 'country', 'company', 'tax_id', 'website', 'service_notifications', ) required = ( 'email', 'first_name', 'last_name', 'address', 'postcode', 'city', 'country', )