如何使用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'})
我的端点/我的/表单有一些内部逻辑来处理'某些事情'。 问题是,当我试图以后访问request.POST.get('某些东西')时,我无法获得任何东西。 我找到了一个解决方案,所以我在下面分享。
答案 0 :(得分:8)
关键是将content_type添加到客户端的post方法,并对数据进行urlencode。
from urllib import urlencode
...
data = urlencode({"something": "something"})
response = self.client.post("/my/form/", data, content_type="application/x-www-form-urlencoded")
希望这有助于某人!
答案 1 :(得分:1)
如果要使用 client 发送有关旧Django版本的字典,则必须定义 content_type ='application / json',因为其内部转换无法处理字典,因此还需要使用 json.dumps 方法像blob一样发送字典,总之下一个必须有效
import pprint
pp = pprint.PrettyPrinter(indent=2)
industry_list = [
{
"parent_ind" : "Clothing",
"name" : "shirt"
},
{
"name": "Clothing"
},
{
"parent_ind" : "Clothing",
"name" : "jeans"
},
{
"parent_ind" : "Clothing",
"name" : "Dress"
},
{
"name": "Digital Products"
},
{
"parent_ind" : "Digital Products",
"name": "computer parts"
},
{
"parent_ind" : "computer parts",
"name": "Hard Disk"
}
]
# Initialize an access tree object
accessTree = {}
# Recursive object search function
def _findItem(obj, key):
if key in obj: return obj[key]
for k, v in obj.items():
if isinstance(v, dict):
item = _findItem(v, key)
if item is not None:
return obj[k][key]
# For each item in the industry list
for listItem in industry_list:
# Recursively check if there is a parent industry
if "parent_ind" in listItem.keys():
parentInd = listItem["parent_ind"]
itemName = listItem["name"]
parentObject = _findItem(accessTree, parentInd)
# If so, add it to the object
if parentObject is not None:
parentObject[itemName] = {}
# Otherwise, add it
elif parentObject is None:
accessTree[parentInd] = {}
accessTree[parentInd][itemName]= {}
print("Final Access Tree as follows: \n")
pp.pprint(accessTree)