[Django]-How to send the javascript list of dictionaries object to django ajax

4👍

Javascript

function AddPropety(){
  var list = [{'name':'parrot','color':'green'},{'name':'dog','color':'brown'},etc...];
  var formData = new FormData($('#submit_form')[0]);

  formData.append("list", JSON.stringify(list));

  $.ajax({
    url: "{% url 'add_details' %}",
    type: 'POST',
    data: formData,
    async: true,
    cache: false,
    contentType: false,
    processData: false,


  });// end of $.ajax

  return false;

}

ajax.py

def add_details(request):
    response_data = {}
    if request.is_ajax():

        lists = request.POST.get('list')
        jd = json.dumps(lists)
        list = eval(json.loads(jd))
        print lists
        for list in lists:  
            print list
        response_data['status'] = "success"

    else:
        response_data['status'] = "Error"

    return HttpResponse(json.dumps(response_data), content_type='application/json')

5👍

var arr = ["a","b",,,"e"];
var json_string = JSON.stringify(arr);

.

   json_string = '[{'name':'parrot','color':'green'},{'name':'dog','color':'brown'},etc...]'  # passed from JavaScrip    try:
   import simplejson as json
   result = json.loads(json_string)

3👍

just use getlist

lists = request.POST.getlist(‘list’)

0👍

In js you have to stringify your array:

let arr = [{"foo1": bar1}, {"foo2": bar2}]
let data = {"data": JSON.stringify(arr)}
$.ajax({
    url: url,
    method: 'POST',
    headers: {"X-CSRFToken": variables.csrfToken},
    data,
})

In views.py you may overide create method if using generic views:

import json
from rest_framework.generics import CreateAPIView

class MyCreateAPIView(CreateAPIView):
    serializer_class = MySerializer

    def create(self, request, *args, **kwargs):
        """
        checks if post request data exists initializes serializer with many=True
        else executes default CreateModelMixin.create method
        """

        json_string_data = request.data.get('data', False)

        if not json_string_data:
            return super(MyCreateAPIView, self).create(request, *args, **kwargs)
        else:
            json_data = json.loads(json_string_data)
            serializer = self.get_serializer(data=json_data, many=True)
            serializer.is_valid(raise_exception=True)
            self.perform_create(serializer)
            headers = self.get_success_headers(serializer.data)
            return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)

Leave a comment