Django:可选模型表单字段 [英] Django: Optional model form field

查看:84
本文介绍了Django:可选模型表单字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的应用程序中有一个模型表单,我希望我的两个模型表单字段是可选的,即用户可以将这两个表单字段留为空白,并且Django表单验证不应为此引发错误.

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.

我为这两个字段设置了blank = Truenull = True,如下所示:

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)

但是,如果提交时将这两个字段留为空白,则会引发This field is required.

However, if these two fields are left blank on submission, a This field is required is raised.

这里似乎有什么问题?如何在Django中设置可选的模型表单字段?

What seems to be wrong here? How can I set optional model form fields in Django?

推荐答案

尝试一下:

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)

这篇关于Django:可选模型表单字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆