Django json字段形成字段

时间:2013-05-16 15:30:41

标签: python django web

我有一个django应用程序,在模型中有一个json字段看起来像这样

from json_field import JSONField
from django.db import models 

class C(models.Model):
    name = models.CharField(max_length=255)
    jf   = JSONField(null=False)

有一个表单显示如下

 class Edit(forms.Form):
     name      = forms.CharField()
     def __init__(self, *args, **kwargs):
         if 'extra' in kwargs:
             extra = kwargs.pop('extra')
             super(Edit, self).__init__(*args, **kwargs)
             for k, v in extra.iteritems():
                  self.fields['%s' % k] = v
         else:
             super(Edit, self).__init__(*args, **kwargs)

该视图将加载json字段jf并将其作为初始数据发送到Form 将所有必要的字段作为额外字段发送。

def edit_model(request, pk):
    obj = get_object_or_404(models.C, pk=pk)
    initial = model_to_dict(obj)
    form = Edit(request.POST or None, initial=initial, extra=initial['jf'])
    if request.method == 'POST':
        if form.is_valid():
            .....
            # what is the best practice here ?
            # intersect cleaned data with the jf fields ?!
            # have an external entity that does this ?!
            # is anything built into django that can help

谢谢!

1 个答案:

答案 0 :(得分:3)

如果我理解你可以尝试this custom widget's form of django它对形式字段和表单字段执行JSON - >保存后的JSON