1
def my_view(request, someid=None):
    if request.method == 'GET':
        # do stuff
        return HttpResponse({})

    elif request.method == 'PUT':
        print request.body
        print request.PUT

        print json.loads(request.body)

        return HttpResponse({})

this is my view and I'm making a PUT request (using Postman-an api simulator) x-www-form-urlencode

when I do request.body it prints all data I'm sending in the form of a=1&b=2&c=3. so when I do json.loads(request.body), it raises value error, no json object could be decoded. thats understandable. json.loads needs a json data.

but when I print request.PUT it says object has no attribute PUT. we generally do request.GET or request.POST, right? but why not 'PUT'?.

so I have two questions-

1) how do I convert this request.body format into python dictionary?

2 why I'm not able to print request.PUT

I have even tried request.POST in the 'PUT' block but its empty.

similar question has been asked here ValueError: No JSON object could be decoded - Django request.body

but its not exactly same this might be having issue in POST block.

apart from this, I need request.body, I don’t want to manually extract field like

put = QueryDict(request.body)
description = put.get('description')
...

there are many fields so i cant do this.

Community
  • 1
  • 1
rocktheparty
  • 217
  • 4
  • 10

1 Answers1

2

try this

from django.http import QueryDict
qd = QueryDict(request.body)
put_dict = {k: v[0] if len(v)==1 else v for k, v in qd.lists()}

. now you can directly update an object by **put_dict

OR

one liner

put_dict = {k: v[0] if len(v)==1 else v for k, v in QueryDict(request.body).lists()}
Gaurav Jain
  • 1,549
  • 1
  • 22
  • 30