0

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

                                                          })
1

2 Answers 2

3

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)
Sign up to request clarification or add additional context in comments.

Comments

0

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

2 Comments

This does not work. Trying to access "nameOfScedule" from my JSON object and I'm getting a 500 error.
Why do you try to access data inside your response object? Can you maybe paste some code?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.