D Malan
D Malan

Reputation: 11414

How to convert a Django HttpRequest object with data to a Django Rest Framework Request object?

I'm trying to turn a django.http.HttpRequest object that contains JSON POST data into a rest_framework.request.Request object, but the data ends up empty.

I was asked to create the HttpRequest using the Django Rest Framework's APIRequestFactory. So I create it like this:

from rest_framework.test import APIRequestFactory
factory = APIRequestFactory()
data = {'email': '[email protected]'}
request =  factory.post('/', data, content_type='application/json')
# also tried using json.dumps(data) instead of just data

And then I try to convert it to a Request object using:

from rest_framework.request import Request
from rest_framework.parsers import JSONParser
converted_request = Request(request, parsers=[JSONParser])

I would expect converted_request.data to contain the data from data, i.e. {'email': '[email protected]'}. However, when in print it, I get <QueryDict: {}>:

>>> print(converted_request.data)
<QueryDict: {}>

The only way I can get the request to contain the data is by setting the _full_data attribute after creating the Request object:

>>> converted_request._full_data = data
>>> print(converted_request.data)
{'email': '[email protected]'}

I'm looking to see if there is a way of populating the request's data without setting the attribute directly. I don't understand why it's not getting populating currently.

Below is the full snippet for easy copy-and-pasting:

from rest_framework.test import APIRequestFactory
factory = APIRequestFactory()
data = {'email': '[email protected]'}
request =  factory.post('/', data, content_type='application/json')

from rest_framework.request import Request
from rest_framework.parsers import JSONParser
converted_request = Request(request, parsers=[JSONParser])

print(converted_request.data)
# <QueryDict: {}>

converted_request._full_data = data

print(converted_request.data)
# {'email': '[email protected]'}

Upvotes: 2

Views: 2367

Answers (1)

D Malan
D Malan

Reputation: 11414

Turns out the parsers need to be instances and not just classes and the data needs to be a JSON string:

import json
from rest_framework.test import APIRequestFactory
factory = APIRequestFactory()
data = {'email': '[email protected]'}
request =  factory.post('/', json.dumps(data), content_type='application/json')

from rest_framework.request import Request
from rest_framework.parsers import JSONParser
converted_request = Request(request, parsers=[JSONParser()])

print(converted_request.data)

Upvotes: 4

Related Questions