【问题标题】:Django POST data dictionary is empty when posting from test client从测试客户端发布时,Django POST 数据字典为空
【发布时间】:2014-03-22 16:22:41
【问题描述】:

我正在尝试在我的 Django 项目中测试和 AJAX 视图。当从 JQuery 提交帖子时,可以在 Django 视图中正确访问数据,但是当我尝试为 Django 测试客户端进行查询时,它是空的。

这是我使用的代码:

观点

def add_item(request):
    if request.is_ajax() and request.method == 'POST':

        post_data = request.POST
        print post_data   ## <----- THIS IS EMPTY

        name = post_data.get('name')

        # Render the succes response
        json_data = json.dumps({"success":1})
        return HttpResponse(json_data, content_type="application/json")
else:
    raise Http404

还有测试

class TestAddItem(TestCase):  
    def test_some_test(self):
        data = {
        'description':"description",      
        }

        response = self.client.post('theurl', data, content_type='application/json')

知道我可能做错了什么吗? 我也尝试不使用内容类型,也尝试使用像thurl/?name=name 这样的普通网址,但没有成功。 任何帮助将不胜感激。

奥利维尔

【问题讨论】:

    标签: ajax django testing


    【解决方案1】:

    在尝试了参数格式、内容类型等的不同组合之后。 我找到了一种可行的解决方案:

    response = self.client.post(reverse('theurl'), data, 
                 **{'HTTP_X_REQUESTED_WITH': 'XMLHttpRequest'})
    

    我在请求的 POST 参数上得到以下字典:

    <QueryDict: {u'name': [u'name']}>
    

    编辑我喜欢测试 :)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-02-27
      • 2018-09-20
      • 2018-12-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多