Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access raw_post_data in django test client

The title pretty much says it all: I use raw_post_data in a couple of views, and thus I need the test client to properly grant access to it.

I have copied the raw_post_data string, from a mock request, passed it to json.loads(), and then used the resulting dict as the POST data for the test client. Then, I set the content type to "application/json" - this causes raw_post_data to appear, but it is not the same raw_post_data as the mock request.

like image 337
jMyles Avatar asked Oct 25 '11 06:10

jMyles


2 Answers

When you change the content type in the test client, the data parameter is not parsed as a dictionary anymore but sent directly. Try copyin your JSON string directly as the data parameter to your post request, you should receive it in raw_post_data in your application.

like image 82
ekse Avatar answered Nov 05 '22 06:11

ekse


Just need to follow the steps as below:
    1. set the data attribute to your string.
    2. then set the content_type attribute to application/octet-stream.

    payload = {'k1':'v1'}
    data = json.dumps(payload)
    response = self.client.post(url, data=data, content_type='application/octet-stream', **self.auth_headers)
like image 44
hupantingxue Avatar answered Nov 05 '22 05:11

hupantingxue