Synthead
Synthead

Reputation: 2321

Django: Make certain fields in a ModelForm required=False

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'

Upvotes: 59

Views: 68136

Answers (5)

rioted
rioted

Reputation: 1102

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.

Upvotes: 50

quin
quin

Reputation: 276

the following may be suitable

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

Upvotes: 5

Valery Ramusik
Valery Ramusik

Reputation: 1573

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

Upvotes: 39

Daniel Silva
Daniel Silva

Reputation: 103

You could try this:

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

requireds must be under Meta.

Upvotes: -17

yedpodtrzitko
yedpodtrzitko

Reputation: 9359

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

Upvotes: 93

Related Questions