Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

POST with None data in Request Factory in Django

I'm moving my django application from 1.x to 2.2, When running unit tests, I get a error about posting None as data. Is it allowed to post None in previous versions? Is there any way to post None via RequestFactory?

I don't want to give a empty string, since the field needs to be validated

r = RequestFactory()
rr = r.post("some-url",{"name":"sri", "kd_ratio":None})

Error:

  File "/usr/local/lib/python3.7/site-packages/django/test/client.py", line 354, in post
    post_data = self._encode_data(data, content_type)
  File "/usr/local/lib/python3.7/site-packages/django/test/client.py", line 313, in _encode_data
    return encode_multipart(BOUNDARY, data)
  File "/usr/local/lib/python3.7/site-packages/django/test/client.py", line 197, in encode_multipart
    'Cannot encode None as POST data. Did you mean to pass an '
TypeError: Cannot encode None as POST data. Did you mean to pass an empty string or omit the value?
like image 319
Sridhar Cr Avatar asked Sep 11 '19 04:09

Sridhar Cr


1 Answers

https://docs.djangoproject.com/en/3.0/topics/testing/tools/#django.test.Client.post

You need to add content_type="application/json" as an argument to be able to send None/null as a value.

The reason is that the default content type (multipart/form-data) doesn't support null values, only empty strings, hence the suggestion.

like image 71
drew Avatar answered Sep 21 '22 05:09

drew