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'
Set the exclude attribute of the ModelForm 's inner Meta class to a list of fields to be excluded from the form.
You have to use self. fields[…]. required = True in the form's constructor to force required behaviour for those fields.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With