在 Django 的请求工厂中使用无数据进行 POST

Sri*_* Cr 6 python django post

我正在将我的 django 应用程序从 1.x 移动到 2.2,在运行单元测试时,我收到关于将 None 作为数据发布的错误。在以前的版本中允许发布 None 吗?有没有办法通过RequestFactory发布None?

我不想给出空字符串,因为该字段需要验证

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

错误:

  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?
Run Code Online (Sandbox Code Playgroud)

dre*_*rew 7

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

您需要添加content_type="application/json"一个参数才能将 None/null 作为值发送。

原因是默认内容类型(multipart/form-data)不支持空值,只支持空字符串,因此建议。