I have a model form in my application, and I want two of my model form fields to be optional, i.e. the users could leave those two form fields blank and the Django form validation shouldn't raise an error for the same.
I have set blank = True
and null = True
for those two fields as follows:
questions = models.CharField(blank=True, null = True, max_length=1280)
about_yourself = models.CharField(blank=True, null = True, max_length=1280)
forms.py
questions = forms.CharField(help_text="Do you have any questions?", widget=forms.Textarea)
about_yourself = forms.CharField(help_text="Tell us about yourself", widget=forms.Textarea)
However, if these two fields are left blank on submission, a This field is required
is raised.
What seems to be wrong here? How can I set optional model form fields in Django?
Try this:
questions = forms.CharField(help_text="Do you have any questions?", widget=forms.Textarea, required=False)
about_yourself = forms.CharField(help_text="Tell us about yourself", widget=forms.Textarea, required=False)
I think this is because you re-define the fields in your Form, so if for example your model name is MyModel, and then you simply define a ModelForm
MyModelForm(forms.ModelForm):
class Meta:
model = MyModel
it will work, but since you defined the fields, it uses the defaults of the django fields.Field, which is required=True
You can simply add required=True to your fields definitions
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