我尝试创建一些集成测试来测试我的 django 项目中的 View 。在我看来,我创建了一个带有前缀
的 ModelFormcustomer_form = CustomerForm(request.POST or None, prefix="customer", instance=customer)
我正在使用 django 客户端在集成测试中尝试以下代码。
response = self.client.get(reverse("customer_edit", kwargs={"customer_id":customer_id})
customer_form = response.context["customer_form"]
data = customer_form.data
prefix = cutomer_form.prefix
self.client.post(reverse("customer-edit", kwargs={"customer_id":customer_id}, data, follow=True)
但在我看来,当我检查 customer_form 是否有效时,我发现它不是。尽管数据字典包含值,但 customer_form.errors 具有所有必填字段。当在模型表单上设置前缀时,django 会做一些不同的事情吗?
最佳答案
您可以从 initial
字典中获取值并手动添加前缀:
data = {"{}-{}".format(prefix, k): v for k, v in customer_form.initial.items()}
关于python - ModelForm 使用的 request.POST 前缀不适用于单元测试中的 client.post,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32573337/