简体   繁体   English

Django:可选模型表单字段

[英]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, ie the users could leave those two form fields blank and the Django form validation shouldn't raise an error for the same.我的应用程序中有一个模型表单,我希望我的两个模型表单字段是可选的,即用户可以将这两个表单字段留空,并且 Django 表单验证不应引发相同的错误。

I have set blank = True and null = True for those two fields as follows:我为这两个字段设置了blank = Truenull = True ,如下所示:

questions = models.CharField(blank=True, null = True, max_length=1280)
about_yourself = models.CharField(blank=True, null = True, max_length=1280)

forms.py表格.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.但是,如果提交时将这两个字段留空,则会引发This field is required的。

What seems to be wrong here?这里似乎有什么问题? How can I set optional model form fields in Django?如何在 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我认为这是因为您重新定义了表单中的字段,所以例如如果您的模型名称是 MyModel,那么您只需定义一个 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它会起作用,但是由于您定义了字段,因此它使用 django fields.Field 的默认值,即 required=True

You can simply add required=True to your fields definitions您可以简单地将 required=True 添加到您的字段定义中

I think u need to add required=False parameter for forms.我认为你需要为表单添加required=False参数。

Like 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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM