How to pass more than one JSON object without getting 400 Bad Request error

I am trying to use Ajax to post to Django and save JSON information in the database. This works when I have only one object stringified and sent, but when I add another I get a 400 Bad request error. I believe this might be due to the way I have the model/view setup?

Here is my code: JSON

var testData2 = '[{"id" : "Home", "parent" : "#", "text" : "Home"}, {"id" : "node3", "parent" : "#", "text" : "test worked yay"}, {"id" : "node2", "parent" : "Home", "text" : "hmm. weird"}]';

Linked to a "save changes" button

$("#postChange").click(function(){
    $.ajax({
      url:/snippets/,
      type:"POST",
      data:testData2,
      contentType:"application/json; charset=utf-8",
      dataType:"json",

    })
});

Django Model

from django.db import models

class StoringJSON(models.Model):
  id = models.TextField(primary_key='true', default='node_1')
  parent = models.CharField(max_length=30, default='#')
  text = models.CharField(max_length=30, default='Node')

Django View

@api_view(['GET', 'POST'])
def tree_list(request):
    """
    List all snippets, or create a new tree.
    """
    if request.method == 'GET':
        trees = StoringJSON.objects.all()
        serializer = TreeSerializer(trees, many=True)
        return Response(serializer.data)

    elif request.method == 'POST':
        serializer = TreeSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

Serializer:

from rest_framework import serializers
from treetool.models import StoringJSON

class TreeSerializer(serializers.ModelSerializer):
    class Meta:
        model = StoringJSON
        fields = ('id', 'parent', 'text')

And for further context, I am using this with jsTree jQuery plugin.

Thank you for any help, if you need more info to help me, let me know, and I will respond promptly.

Answers 1

  • If you are serializing multiple you likely need to pass many=True to TreeSerializer again (inside your POST check).

    Also, I am surprised that passing primary_key='true' works at all, it should be written as primary_key=True.


Related Articles