Create a Mock Request for django rest framework

I am trying to createa mock Request for a post method in django rest framework and tried:

factory = APIRequestFactory()
data = {"hello": 1}
print(data)

django_request = factory.post(url, data, format="json")
print("body:", django_request.body)
print("ct:", django_request.content_type)
r = Request(django_request)
print(r.data)

The printing correctly shows the body to be set to a (binary) string. However the final r.data is an empty list. How do I set the data?

Assumed that you have a DRF view as follow

from rest_framework.decorators import api_view
from rest_framework.response import Response

@api_view(["POST"])
def hello_world(request):
    return Response("Hello World")

what you should do is to pass request object as input to view function:

from rest_framework.test import APIRequestFactory
request = factory.post(url, data, format="json")
response = hello_world(request)
print(response.data)
# -> Hello World

Вернуться на верх