[POST在Django的Request Factory中没有数据

问题描述 投票:3回答:1

我将Django应用程序从1.x移到2.2,运行单元测试时,出现关于将None作为数据发布的错误。可以在以前的版本中发布None吗?有什么方法可以通过RequestFactory发布None吗?

我不想提供一个空字符串,因为该字段需要验证

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

错误:

  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?
python django post
1个回答
0
投票

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

您需要添加content_type="application/json"作为参数,以便能够将None / null作为值发送。

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

© www.soinside.com 2019 - 2024. All rights reserved.