56

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'
3
  • There's no form field type called TextArea, you have to use an ancestor of Field, probably the one called CharField and add a TextArea widget Jun 4, 2014 at 18:45
  • Would it be possible to set the field to required=False without defining a static field and/or widget type?
    – Synthead
    Jun 4, 2014 at 18:48
  • possible duplicate of Django required field in model form Aug 5, 2015 at 22:10

5 Answers 5

91

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
1
46

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.

4
  • This should be the accepted answer since it is what blank is intended for
    – dnaranjo
    Jun 29, 2016 at 13:15
  • 7
    This is not always the solution: Imagine you have a field in a model that is compulsory, but you want to search for objects of that type with or without this restriction. Then you want the form to allow a search without that attribute. For instance you have colour as a required field in the model, but you might want search for objects that have a certain shape, regardless of the colour. Sep 26, 2016 at 18:03
  • No solution is always the solution. But the solution I have presented is the best practice that ought to be used unless your situation is unusual (like the one you mentioned). In that case, a separate SO question would make sense. But OP doesn't mention any such situation, the question is very general and so should be the answer.
    – rioted
    Oct 4, 2016 at 11:19
  • 4
    No, this solution is special solution, It’s a very common situation that you have a model with some required fields, e. g. addresses with street, city, country all compulsory, but you want to search with a form (ModelForm) for just a part of the fields, e. g. just city and country. And I understood the OP like that. Your solution, that is very obvious for me, that you define the model fields as blank=True (sometimes in combination with null=True) works just in special cases. The general answer is the one by yedpodtrzitko. Feb 9, 2017 at 12:57
32

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',
        )
7
  • Everything works like a charm. @SandeepBalagopal could you explain what exactly went wrong and show error? May 8, 2019 at 14:45
  • tried this and the fields did not become required. If you look into the options in modelform, modelform is not having such an option github.com/django/django/blob/master/django/forms/… May 9, 2019 at 6:27
  • @SandeepBalagopal, do you want to tell that people voted here stackoverflow.com/a/24045492/5992385 and here stackoverflow.com/a/1429646/5992385 are wrong May 10, 2019 at 10:27
  • 5
    I didn't notice the init method you have overriden. It works. Sorry for the mixup. May 13, 2019 at 5:41
  • 1
    @isilanes You sad "I believe that all fields in a ModelForm are required by default". But not all. Weather field is required on a ModelForm depends on the field parameters on its Model. And sometimes we need override such behavior by making non required field required. Jul 15, 2020 at 10:16
5

the following may be suitable

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

You could try this:

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

requireds must be under Meta.

1
  • 2
    Did you actually use this? Because I see no indication in the Django docs or source code, that this would work.
    – Daniel
    Dec 21, 2017 at 9:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.