Reputation: 4511
I am trying to parse json object in my Django view which has been passed through from client by ajax via post method.
JS:
$.post ('/update_vendor_merchandise_types/', JSON.stringify(json_obj))
;
View:
def update_vendor_merchandise_types(request):
print json_object
# The output gives me
# QueryDict: <QueryDict: {u'[{"merchandise_id":"3"},{"merchandise_id":"4"}]': [u'']}>
json_object = json.load(request.POST) # Error arises
pass
On the commented line 'QueryDict' object has no attribute 'read' error
arises.
What am I doing wrong ?
Eventually, my goal is to get access to merchandise_id values. I try
d = request.POST.iteritems()
for key, value in d:
print value
and expect something like
3
4
Upvotes: 3
Views: 2763
Reputation: 1283
Why do you convert json_obj into string when sending it to server? I think you should do it in this way:
json_obj = {"key1": "value1", "key2": "value2"}
$.post('/update_vendor_merchandise_types/', json_obj)
In this case on the server side you can access sent data in this way:
v1 = request.POST["key1"]
Upvotes: 4
Reputation: 599876
request.POST
is for form-encoded content. For JSON, you should access the plain body directly:
json_object = json.loads(request.body)
Upvotes: 4