如何创建 Django ModelForm,以便它的字段有时是必需的,有时不是?
好的,问题来了。 想象一下我有一个只有两个字段的 ModelForm。像这样:
class ColorForm(forms.Form):
color_by_name = forms.CharField()
color = forms.IntegerField(widget = forms.Select(choices=COLOR_CHOICES))
用户可以输入颜色名称,也可以从列表中选择它。颜色是必需的,但这并不意味着用户应该手动输入。我在那里放置验证,以便我的代码检查用户是否在下拉列表中选择了颜色,如果没有,那么他应该手动编写它?
Ok, here is the question.
Imagine I have a ModelForm which have only two fields. like this one:
class ColorForm(forms.Form):
color_by_name = forms.CharField()
color = forms.IntegerField(widget = forms.Select(choices=COLOR_CHOICES))
So a user can either input a color name, a choose it from a list. Color is required, but that doesn't mean, that user should enter it manually. There do I put validation, so that my code checks if user selected color in dropdownlist and if not then he should write it manually?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
将它们设置为
required=False
,但编写一个clean()
方法来检查其中之一。请参阅 验证文档作为示例。Make them both
required=False
, but write aclean()
method which checks for one or the other. See the validation documentation for an example.