C. Gary
C. Gary

Reputation: 123

How to Parse JSON object in Django View from Ajax POST

I'm currently submitting data via a POST request using the below jquery ajax method and I'm successfully getting a return result in my console (see below) that displays the JSON request that was submitted to the server. However I CANNOT figure out how to parse the JSON object in my Django view. What do I write my view so I can Parse my JSON object and get a hold of "schedule_name" to execute the below command in my Django view. Please see a copy of my view below.

Schedule.objects.create(schedule_name = Schedule)

$.ajax({

type: "POST",
url: "{% url 'addSchedule' building_pk %}",
dataType: "json",
data: {"json_items" : JSON.stringify(Schedule_Info)},
success : function(data) 
  {
    $('.todo-item').val(''); // remove the value from the input
    console.log(data); // log the returned json to the console
    console.log("success"); // another sanity check
    alert("Sucess");
     
  },

JSON output in console after submitting request

json-items: "{

"nameOfSchedule":{"schedule_name":"Schedule"},

"Rooms":[
	{"room_rank":"1","room_name":"Room 101 "},
	{"room_rank":"2","room_name":"Room 102 "},
	{"room_rank":"3","room_name":"Room 103 "},
	{"room_rank":"4","room_name":"Room 104 "}
	],

"Users":[
	{"user_name":"[email protected]"},
	{"user_name":"[email protected]"}
	]
}"

Django View

def addSchedule(request, building_id):

    building_pk = building_id

    b = Building.objects.get(pk=building_pk)
    floor_query = b.floor_set.all()
    master_query = floor_query.prefetch_related('room_set').all()

    if request.is_ajax() and request.POST:
        data = request.POST

    ### Input the schedule name in the datase by parsing the JSON object

        return HttpResponse(json.dumps(data),content_type="application/json")

    else:
        return render(request, 'scheduler/addSchedule.html', {'building_pk' : building_pk,
                                                        'building_query': master_query

                                                          })

Upvotes: 0

Views: 3275

Answers (2)

C. Gary
C. Gary

Reputation: 123

I resolved the issue by making the following changes to my Django

Django view

data = json.loads(request.POST.get('json_items'))

name = data['nameOfSchedule']['schedule_name']
Schedule.objects.create(schedule_name = name)

Upvotes: 3

Arron
Arron

Reputation: 916

You could use the JsonResponse for that:

return JsonResponse({'this': "will be converted to json"});

See https://docs.djangoproject.com/el/1.10/ref/request-response/ for more info

Upvotes: 0

Related Questions