Reputation: 1752
When trying to test apis that are decorated with @api_view
I receive a format that does not match to the response when testing it manually. I expect the following format:
{
"field": "string value"
}
but when I try to post(from tests) I receive error because the format appears to be this one:
{
"field": ["string_value"]
}
To reproduce this problem:
class Tests(rest_framework.test.APITestCase):
def test_api(self):
...
response = self.client.post(url, data)
...
Upvotes: 2
Views: 1448
Reputation: 1115
You can also set a default format in settings.py
with:
REST_FRAMEWORK = {
'TEST_REQUEST_DEFAULT_FORMAT': 'json',
...
}
... Meaning you don't have to set it with each request.
Upvotes: 3
Reputation: 1020
response = self.client.post(url, data, format='json')
Make sure to add this to your code. The format='json'
part is important because I assume your endpoint is set to receive it. Your endpoint is not smart enough to recognize what format you're sending it in, but it recognizes whether it's in the format you've set it to be :) You can override this by adding a parser_class=(JSONParser,))
or @parser_classes((JSONParser,))
to your APIView
/@apiview
.
Check your settings.py
file for this line.
REST_FRAMEWORK = {
'DEFAULT_PARSER_CLASSES': (
'rest_framework.parsers.JSONParser',
)
}
http://www.django-rest-framework.org/api-guide/parsers/
Upvotes: 0