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

一笑奈何 提交于 2021-02-09 10:53:13

问题


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

回答1:


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

json_object = json.loads(request.body)



回答2:


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"]


来源:https://stackoverflow.com/questions/37569716/handling-ajax-json-object-in-django-querydict-object-has-no-attribute-read

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!