【问题标题】:Django test Client submitting a form with a POST requestDjango 测试客户端使用 POST 请求提交表单
【发布时间】:2018-03-09 00:51:09
【问题描述】:

如何使用 Django 测试客户端提交 POST 请求,以便在其中包含表单数据? 特别是,我想要类似的东西(灵感来自How should I write tests for Forms in Django?):

from django.tests import TestCase

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

我的端点 /my/form 有一些内部逻辑来处理“某事”。 问题是当尝试稍后访问 request.POST.get('something') 时,我什么也得不到。 我找到了解决方案,所以我在下面分享。

【问题讨论】:

    标签: python django django-testing


    【解决方案1】:

    关键是在客户端的post方法中加入content_type,同时对数据进行urlencode。

    from urllib import urlencode
    
    ...
    
    data = urlencode({"something": "something"})
    response = self.client.post("/my/form/", data, content_type="application/x-www-form-urlencoded")
    

    希望这对某人有所帮助!

    【讨论】:

    • 您不需要对帖子数据进行 urlencode 或设置内容类型。 client.post() 文档中的示例表明您的问题中的 response = self.client.post("/my/form/", {'something':'something'}) 应该可以工作。也许你从你的问题中错过了一些可以解释为什么它不起作用的东西。
    • 我只能使用 urlencode 让它在 django 1.11 上工作
    【解决方案2】:

    如果您使用 client 在旧 django 版本上发送字典,则必须定义 content_type='application/json' 因为其内部转换无法处理字典,还需要使用 json.dumps 方法像 blob 一样发送字典,总之,下一个必须有效

    import json
    from django.tests import TestCase
    
    class MyTests(TestCase):
        def test_forms(self):
            response = self.client.post("/my/form/", json.dumps({'something':'something'}), content_type='application/json')
    
    

    【讨论】:

      【解决方案3】:

      如果您将 content_type 提供为 application/json,则如果数据是字典、列表或元组,则使用 json.dumps() 序列化数据。序列化默认使用DjangoJSONEncoder 执行,并且可以通过向Client 提供json_encoder 参数来覆盖。这种序列化也发生在 put()、patch() 和 delete() 请求中。

      【讨论】:

        猜你喜欢
        • 2019-08-07
        • 2018-05-16
        • 2014-01-28
        • 1970-01-01
        • 2022-06-20
        • 2014-10-10
        • 2021-01-09
        • 2016-11-26
        • 2020-01-25
        相关资源
        最近更新 更多