Django: Optional model form field

╄→гoц情女王★ 提交于 2020-05-15 07:47:21

问题


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?


回答1:


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)



回答2:


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



来源:https://stackoverflow.com/questions/31539694/django-optional-model-form-field

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!