[英]ModelForm won't validate because missing value, but model field has null=True
I have a problem where my ModelForm
is trying to assign ''
to a field (it saves fine if I actually provide the primary key of the Product
, but it's not a compulsory field, and won't save if the field is left blank). 我有一个问题,我的
ModelForm
试图将''
分配给一个字段(如果我实际上提供了Product
的主键,它可以很好地保存,但它不是必填字段,并且如果将该字段留空则不会保存) 。 I take it that the ORM it's trying to set that field to ''
but: 我认为ORM试图将该字段设置为
''
但是:
''
be coerced to None
, and; ''
强制为None
,并且; None
in the first place instead of ''
? None
摆在首位,而不是''
? models.py models.py
class Question(models.model):
fk_product = models.ForeignKey(Product, on_delete=models.SET_NULL, null=True, related_name="product_question")
forms.py forms.py
class QuestionForm(forms.ModelForm):
fk_product=forms.ChoiceField(required=False)
class Meta:
model = Question
fields = ['fk_product',]
The error: 错误:
Cannot assign "''": "Question.fk_product" must be a "Product" instance.
无法分配“''”:“ Question.fk_product”必须是“ Product”实例。
The view code that produces the error: 产生错误的视图代码:
QuestionModelFormset = modelformset_factory(Question,
form=QuestionForm,
extra=1)
question_formset = QuestionModelFormset(
data=request.POST,
files=request.FILES,
queryset=Question.objects.all())
if not question_formset.is_valid(): #error occurs on this line
Try adding blank=True
too. 也尝试添加
blank=True
。
null=True
means that this field is allowed to be NULL in database. null=True
表示该字段在数据库中允许为NULL。
blank=True
means it can be submitted without a value in forms. blank=True
表示可以不带任何值的形式提交。 Otherwise it must have value. 否则,它必须具有价值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.