Django如何使用SplitJSONWidget保存/编辑json

时间:2016-08-09 10:38:33

标签: json django django-views

我正在使用Django 1.9和library如下:

models.py:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="menu">
     

        <div class="link" id="joinLink"><a href="joinPage.html">Join </a></div>
        <div class="link" id="returnsLink"><a href="returns.html">Returns</a></div>
        <div class="link" id="methodsLink"><a href="methods.html">Methods</a></div>
    </div>
    <img class="icon-menu" src="https://cdn1.iconfinder.com/data/icons/web-ui-2/16/UI_Icons_Outline-29-128.png"/>

    <img class="icon-close" src="http://s3.amazonaws.com/codecademy-content/courses/ltp2/img/uber/close.png"/>

forms.py:

class Policy(models.Model):
    config = JSONField(max_length=50000, blank=True)
    name = models.CharField(max_length=200, blank=False, unique=True, default="")

    def __unicode__(self):
        return self.name

views.py:

class PolicyForm(forms.ModelForm):
    class Meta:
        model = Policy
        fields = ('name',)

    attrs = {'class': 'special', 'size': '25'}
    data = forms.CharField(widget=SplitJSONWidget(attrs=attrs, debug=True))

我在保存和编辑json时遇到问题:

存储

enter image description here

第一次编辑:

enter image description here

第二次编辑:

enter image description here

正如您所看到的,json与自身连接并将crf标记和名称添加到json(wtf?)。保存和编辑功能有什么问题?

1 个答案:

答案 0 :(得分:0)

问题在于保存过程,解决方案是:

post = form.save(commit=False)
post.config = form.cleaned_data['data']
post.save()

在policy_new()和policy_edit()函数中。