Django: Make certain fields in a ModelForm required=False

Synthead picture Synthead · Jun 4, 2014 · Viewed 40.9k times · Source

How do I make certain fields in a ModelForm required=False?

If I have:

class ThatForm(ModelForm):
  class Meta:
    widgets = {"text": Textarea(required=False)}

Or if I have:

class ThatForm(ModelForm):
  text = Textarea(required=False)

Django returns:

__init__() got an unexpected keyword argument 'required'

Answer

yedpodtrzitko picture yedpodtrzitko · Jun 4, 2014

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