Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/django/21.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/video/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ajax django:使用json对象测试基于POST的视图_Ajax_Django_Json_Unit Testing - Fatal编程技术网

Ajax django:使用json对象测试基于POST的视图

Ajax django:使用json对象测试基于POST的视图,ajax,django,json,unit-testing,Ajax,Django,Json,Unit Testing,我有一个django应用程序,其中有几个视图通过POST请求接受json对象。json对象是中等复杂的,有几层嵌套,因此我使用json库来解析原始的post数据,如下所示: def handle_ajax_call(request): post_json = json.loads(request.raw_post_data) ... (do stuff with json query) 接下来,我想为这些视图编写测试。不幸的是,我不知道如何将json对象传递给客户端。下面是我

我有一个django应用程序,其中有几个视图通过POST请求接受json对象。json对象是中等复杂的,有几层嵌套,因此我使用json库来解析原始的post数据,如下所示:

def handle_ajax_call(request):
    post_json = json.loads(request.raw_post_data)

    ... (do stuff with json query)
接下来,我想为这些视图编写测试。不幸的是,我不知道如何将json对象传递给客户端。下面是我的代码的一个最简单的案例版本:

def test_ajax_call(self):
    c = Client()
    call_command('loadfixtures', 'temp-fixtures-1') #Custom command to populate the DB

    J = {
      some_info : {
        attr1 : "AAAA",
        attr2 : "BBBB",
        list_attr : [ "x", "y", "z" ]
      },
      more_info : { ... },
      info_list : [ 1, 22, 23, 24, 5, 26, 7 ]
    }

    J_string = json.dumps(J)
    response = c.post('/ajax/call/', data=J_string )
当我运行测试时,它失败,原因是:

AttributeError: 'str' object has no attribute 'items'
如何在Client.post方法中传递JSON对象?

似乎暗示,如果将
content\u type
参数传递给
Client.post
,它会将
数据
值视为一个文档并直接发布。所以试试这个:

response = c.post('/ajax/call/', content_type='application/json', data=J_string)

令人惊叹的!感谢您解码文档中的细节。它从来没有特别提到json,所以在我的任何搜索中都没有提到它。因此,如果您在request.META['CONTENT_TYPE']中使用类似于'application/json'的东西来检测调用是否为Ajax,Daniel的解决方案还有一个额外的好处,即正确设置内容类型标题。这是我在添加内容类型时收到的帖子信息:
,因此所有数据都成为关键,这似乎不对。@Hassek您一定没有像上面的问题那样转储json字符串。在我做了一个
json.dumps(数据)