Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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' 
like image 678
Synthead Avatar asked Jun 04 '14 18:06

Synthead


People also ask

How do you exclude a specific field from a ModelForm?

Set the exclude attribute of the ModelForm 's inner Meta class to a list of fields to be excluded from the form.

How do you make a model field required in Django?

You have to use self. fields[…]. required = True in the form's constructor to force required behaviour for those fields.

Why we use commit false in Django?

This save() method accepts an optional commit keyword argument, which accepts either True or False. If you call save() with commit=False , then it will return an object that hasn't yet been saved to the database. In this case, it's up to you to call save() on the resulting model instance.


1 Answers

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 
like image 178
yedpodtrzitko Avatar answered Oct 04 '22 03:10

yedpodtrzitko