python - ModelForm 使用的 request.POST 前缀不适用于单元测试中的 client.post

标签 python django django-unittest

我尝试创建一些集成测试来测试我的 django 项目中的 View 。在我看来,我创建了一个带有前缀

的 ModelForm
customer_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/

相关文章:

python - 用 Python 列表中的值交换索引?

python - 在 macOS Lion 上构建 pytable

Django:迁移表 'forum_user'已存在

python - 单元测试 Django 时区感知日期时间

python 单元测试: assertEqual on same objects throwing AssertionError

Python Django 测试两个异常之一

python - .pxd 文件出现未知文件类型错误

python - 如何计算一个实体与另一个实体一起出现的次数

python - 从 Django 打印时出现 UnicodeEncodeError

Django-Rest-Framework - 嵌套对象和序列化器,如何?