Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django Rest Framework: empty request.data

I have the following code for a view of DRF:

from rest_framework import viewsets

class MyViewSet(viewsets.ViewSet):

    def update(self, request, pk = None):
        print pk
        print request.data

I call the URL via python-requests in the following way:

import requests
payload = {"foo":"bar"}
headers = {'Content-type': 'application/json'}
r = requests.put("https://.../myPk", data= payload, headers=headers)

but when the request is received from the server, request.data is empty. Here there is the output:

myPk
<QueryDict: {}>

How can I fix this problem?

like image 286
floatingpurr Avatar asked Jun 05 '15 16:06

floatingpurr


3 Answers

You need to send the payload as a serialized json object.

import json
import requests
payload = {"foo":"bar"}
headers = {'Content-type': 'application/json'}
r = requests.put("https://.../myPk/", data=json.dumps(payload), headers=headers)

Otherwise what happens is that DRF will actually complain about:

*** ParseError: JSON parse error - No JSON object could be decoded

You would see that error message by debugging the view (e.g. with pdb or ipdb) or printing the variable like this:

def update(self, request, pk = None):
    print pk
    print str(request.data)
like image 60
sthzg Avatar answered Sep 23 '22 05:09

sthzg


Check 2 issues here:-

  1. Json format is proper or not.
  2. Url is correct or not(I was missing trailing backslash in my url because of which I was facing the issue)

Hope it helps

like image 36
Harkirat Saluja Avatar answered Sep 23 '22 05:09

Harkirat Saluja


Assuming you're on a new enough version of requests you need to do:

import requests

payload = {"foo":"bar"}
r = requests.put("https://.../myPk", json=payload, headers=headers)

Then it will properly format the payload for you and provide the appropriate headers. Otherwise, you're sending application/x-www-urlformencoded data which DRF will not parse correctly since you tell it that you're sending JSON.

like image 39
Ian Stapleton Cordasco Avatar answered Sep 21 '22 05:09

Ian Stapleton Cordasco