Rada Rada - 3 months ago 10
JSON Question

Django how to save/edit json with SplitJSONWidget

I`m using Django 1.9 with this library as following:

models.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


forms.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))


views.py:

def policy_new(request):
json = {
"all": {
"active": True
}
}
if request.method == "POST":
form = PolicyForm(request.POST)
if form.is_valid():
post = form.save(commit=False)
post.config = form.data
post.save()
return redirect('ui:config-list')
else:
form = PolicyForm(initial={'data': json})

template = 'api/policy_template.html'
context = RequestContext(request, {'form': form})
return render_to_response(template, context)


def policy_edit(request, pk):
policy = get_object_or_404(Policy, pk=pk)
if request.method == "POST":
form = PolicyForm(request.POST, instance=policy)
if form.is_valid():
post = form.save(commit=False)
post.config = form.data
post.save()
return redirect('ui:config-list')
else:
form = PolicyForm(instance=policy, initial={'data': policy.config})
return render(request, 'api/policy_template.html', {'form': form})


I have a problem with saving and editing the json:

Saving:

enter image description here

Editing first time:

enter image description here

Editing second time:

enter image description here

As you can see the json is concatenating with itself and adding the crf token and the name to the json (wtf?). What is wrong with the saving and editing functions?

Answer

The problem was in the saving process and the solution is :

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

In both policy_new() and policy_edit() functions.

Comments