Edgar Navasardyan Edgar Navasardyan - 6 months ago 28
Ajax Question

Handling ajax json object in Django - 'QueryDict' object has no attribute 'read' error

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

Answer

request.POST is for form-encoded content. For JSON, you should access the plain body directly:

json_object = json.loads(request.body)