json - DJANGO:如何将表单值序列化为 json 以存储在数据库列中

标签 json django forms serialization

我正在做一个项目,我需要将输入到表单中的信息作为 json 存储到数据库列中。该表单没有自己的模型,但它的所有值都将作为 json 存储到另一个模型的列中。这是模型:

class Document(models.Model):
    user = models.ForeignKey(User)
    document = models.JSONField(default = {})
    category = models.CharField(max_length=255)

现在我需要将来自不同形式(不同的 category)的 json 数据存储到 document 列中。以下是此类形式的一类:

class InformalLetterForm(forms.Form):
    sender_name = forms.CharField(max_length=45)
    sender_address = forms.CharField(max_length=255)
    date = forms.DateTimeField()
    message_body = forms.CharField()
    receiver_name = forms.CharField(max_length=255)

我如何将以这种形式输入的数据序列化为 json 对象以存储在数据库列(即上面的 document 列)中。

我在网上搜索过,但我看到只对来自模型表单的数据进行了序列化。 感谢您的帮助..

最佳答案

您可以调用.cleaned_data来自表单的属性,它将返回一个包含表单数据的python字典,然后你可以调用.dumps() json python 库中的方法。让我们从文档中举一个例子:

>>> data = {'subject': 'hello',
...         'message': 'Hi there',
...         'sender': 'foo@example.com',
...         'cc_myself': True}
>>> f = ContactForm(data)
>>> f.is_valid()
True
>>> f.cleaned_data
{'cc_myself': True, 'message': 'Hi there', 'sender': 'foo@example.com', 'subject': 'hello'}

这里有一个包含数据的字典,现在让我们把它变成一个 json:

import json

# An example simple dict
d = {'a': 1, 'b': 2}

json.dumps(d)

# '{"a": 1, "b": 2}'

关于json - DJANGO:如何将表单值序列化为 json 以存储在数据库列中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36286581/

相关文章:

php - 在 symfony2 中创建自定义表单类型 : can't overwrite buildView()

forms - 如何为选择标签元素设置类?

javascript - 表单输入检查Javascript

arrays - 类型 'String' 不符合协议(protocol) 'NSCopying' - 数组 swift json 错误

java - 如何根据条件获取 JSON 值

python - Ansible - 对输出应用过滤器,然后注册为变量

python - 用django自己加入postgresql

json - 在 Go 开发中过度使用 map[string]interface{}?

python - 如何在 Django 服务器启动时打印 ascii 横幅?

python - Django - 实现线程注释的正确方法