Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

POST document with Django RequestFactory instead of form data

I'd like to build a request for testing middleware, but I don't want POST requests to always assume I'm sending form data. Is there a way to set request.body on a request generated from django.test.RequestFactory?

I.e., I'd like to do something like:

from django.test import RequestFactory
import json

factory = RequestFactory(content_type='application/json')
data = {'message':'A test message'}
body = json.dumps(data)
request = factory.post('/a/test/path/', body)

# And have request.body be the encoded version of `body`

The code above will fail the test because my middleware needs the data to be passed as the document in request.body not as form data in request.POST. However, RequestFactory always sends the data as form data.

I can do this with django.test.Client:

from django.test import Client
import json

client = Client()
data = {'message':'A test message'}
body = json.dumps(data)
response = client.post('/a/test/path/', body, content_type='application/json')

I'd like to do the same thing with django.test.RequestFactory.

like image 993
Jay Avatar asked Mar 15 '18 17:03

Jay


2 Answers

RequestFactory has built-in support for JSON payloads. You don't need to dump your data first. But you should be passing the content-type to post, not to the instantiation.

factory = RequestFactory()
data = {'message':'A test message'}
request = factory.post('/a/test/path/', data, content_type='application/json')
like image 123
Daniel Roseman Avatar answered Oct 13 '22 00:10

Daniel Roseman


I've tried Jay's solution and didn't work, but after some reseach, this did (Django 2.1.2)

factory = RequestFactory()    
request = factory.post('/post/url/')
request.data = {'id': 1}
like image 26
Saigesp Avatar answered Oct 13 '22 02:10

Saigesp