本文介绍了从测试客户端发布时,Django POST数据字典为空的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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



这是代码我使用:



视图

  def add_item(request):
如果request.is_ajax()和request.method =='POST':

post_data = request.POST
print post_data ##< -----这是EMPTY

name = post_data.get('name')

#渲染成功响应
json_data = json.dumps({ success:1})
return HttpResponse(json_data,content_type =application / json)
else:
raise Http404

测试

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

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

任何想法我可能做错了什么?
我也尝试没有内容类型,也使用像 thurl /?name = name 没有成功的纯网址。
任何帮助将不胜感激。



Olivier

解决方案

尝试不同组合的参数格式化,内容类型等。
我发现一个解决方案是有效的:

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

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

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

编辑我喜欢测试:)


I am trying to test and AJAX view in my Django Project. When submit the post from JQuery the data is correctly accessible in the Django View but when I try to make queries for the Django test client it is emplty.

Here is the code I use:

The view

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

And the test

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

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

Any Idea what I might be doing wrong?I tried also without content type and also using plain url like thurl/?name=name without succes.Any help will be appreciated.

Olivier

解决方案

After trying different combinations of parameter formating, content types, etc..I found one solution that works :

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

And I get the following dictionary on the POST parameters of the request:

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

Edit I love testing :)

这篇关于从测试客户端发布时,Django POST数据字典为空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-12 18:18