Django: Make certain fields in a ModelForm required=False

DjangoFormsFieldRequiredModelform

Django Problem Overview


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'

Django Solutions


Solution 1 - Django

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

Solution 2 - Django

you ought to add blank=True to the corresponding model

The documentation says > 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.

Solution 3 - Django

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',
        )

Solution 4 - Django

the following may be suitable

class ThatForm(ModelForm):
    text = forms.CharField(required=False, widget=forms.Textarea)

Solution 5 - Django

You could try this:

class ThatForm(ModelForm):
  class Meta:
    requireds = 
    {
       'text':False,
    }

requireds must be under Meta.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSyntheadView Question on Stackoverflow
Solution 1 - DjangoyedpodtrzitkoView Answer on Stackoverflow
Solution 2 - DjangoriotedView Answer on Stackoverflow
Solution 3 - DjangoValery RamusikView Answer on Stackoverflow
Solution 4 - DjangoquinView Answer on Stackoverflow
Solution 5 - DjangoDaniel SilvaView Answer on Stackoverflow