问题描述
在我的模型defn中我有
in my model defn i have
from django.contrib.postgres.fields import JSONField
.....
.......
.........
media_data=JSONField(default=dict)
我创建了默认管理员
当我尝试保存而不触摸字段时,我收到此字段为必填项
错误。
When i attempt to save without touching the field, i get a this field is required
error.
这看起来像是表单验证问题,因为我可以以编程方式从代码中保存模型实例,而不会出现问题。
It looks like a form validation issue because I can programatically save the model instance from code without issue.
为什么会这样?
我错过了一些愚蠢的事情吗?
Why is this happening?
have i missed something silly?
推荐答案
- 发生了什么事。深入源代码时,
。我们可以看到以下调用堆栈:
1) form.is_valid()
->form.full_clean()
-->form._clean_fields()
---> self.cleand_data[name] = field.clean(value)
2) field.clean(value)
-> self.to_python(value)
-> self.validate(value)
查看源代码时,您会发现,这主要是因为 empty_values
支票。
when look into the source code ,you can find that,it's mainly because the empty_values
check.
# These values, if given to validate(), will trigger the self.required check.
EMPTY_VALUES = (None, '', [], (), {})
如您所见,空字典 {}
是JSONField的空值。
as you can see the empty dict {}
is as an empty value for JSONField. so it will raise Error.
- 我们该怎么办?
解决方案是自定义models.JSONField和form.JSONField,如下所示。
forms.py
from django.contrib.postgres import forms
class MyJSONField(forms.JSONField):
empty_values = [None, "", [], ()]
db /fields.py
db/fields.py
class MyJSONField(JSONField):
def formfield(self, **kwargs):
from ..forms import MyJSONField
return super().formfield(**{"form_class": MyJSONField, **kwargs})
这篇关于Django Admin:JSONField默认为空dict不会保存在admin中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!