Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django: Optional model form field

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?

like image 657
Manas Chaturvedi Avatar asked Jul 21 '15 12:07

Manas Chaturvedi


2 Answers

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)
like image 50
Geo Jacob Avatar answered Sep 19 '22 02:09

Geo Jacob


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

like image 22
Galia Ladiray Weiss Avatar answered Sep 21 '22 02:09

Galia Ladiray Weiss