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

我有一个django应用程序与几个视图通过POST请求接受json对象。 json对象是中等复杂的几层嵌套,所以我使用json库解析raw_post_data,如下所示:
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对象?

The documentation似乎暗示如果你将一个content_type参数传递给client.post,它会将数据值视为文档并直接POST。所以试试这个:
response = c.post('/ajax/call/',content_type='application/json',data=J_string)

相关文章

$.AJAX()方法中的PROCESSDATA参数 在使用jQuery的$.ajax()方...
form表单提交的几种方式 表单提交方式一:直接利用form表单提...
文章浏览阅读1.3k次。AJAX的无刷新机制使得在注册系统中对于...
文章浏览阅读1.2k次。 本文将解释如何使用AJAX和JSON分析器在...
文章浏览阅读2.2k次。/************************** 创建XML...
文章浏览阅读3.7k次。在ajax应用中,通常一个页面要同时发送...