Django Admin:JSONField默认为空dict不会保存在admin中 [英] Django Admin: JSONField default empty dict wont save in admin

查看:299
本文介绍了Django Admin:JSONField默认为空dict不会保存在admin中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的模型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. 发生了什么事。深入源代码时,
    。我们可以看到以下调用堆栈:



    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.


  1. 我们该怎么办?
    解决方案是自定义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中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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