Django测试客户端提交带有POST请求的表单

MMa*_*ian 6 python django django-testing

如何使用Django测试客户端提交POST请求,以便在其中包含表单数据?特别是,我希望有类似的东西(灵感来自我应该如何在Django中为Forms编写测试?):

from django.tests import TestCase

class MyTests(TestCase):
    def test_forms(self):
        response = self.client.post("/my/form/", {'something':'something'})
Run Code Online (Sandbox Code Playgroud)

我的端点/ my/form有一些内部逻辑来处理'某事'.问题是,当试图以后访问request.POST.get('something')时,我无法得到任何东西.我找到了一个解决方案,所以我在下面分享.

MMa*_*ian 9

关键是将content_type添加到客户端的post方法,并对数据进行urlencode.

from urllib import urlencode

...

data = urlencode({"something": "something"})
response = self.client.post("/my/form/", data, content_type="application/x-www-form-urlencoded")
Run Code Online (Sandbox Code Playgroud)

希望这有助于某人!

  • 从urllib.parse导入urlencode的Python 3 (4认同)
  • 您不需要对帖子数据进行urlencode或设置内容类型.[`client.post()`](https://docs.djangoproject.com/en/1.11/topics/testing/tools/#django.test.Client.post)文档中的示例显示`response = self.client.post("/ my/form /",{'something':'something'})`来自你的问题应该有效.也许你错过了一些问题,这可以解释为什么它不起作用. (3认同)
  • 这对于我尝试构建“application/x-www-form-urlencode”内容类型的数据非常有帮助。除了 Python 3 中的“from urllib.parse import urlencode” (2认同)