【发布时间】:2018-02-09 14:41:46
【问题描述】:
我要么错过了一些非常简单的东西(而且我的 Google-Fu 也没有),要么我偏离了轨道。你打电话!
我想编写一个测试来练习将表单集发布到视图。
# get the modelformset from the view
response = self.client.get("/myview")
formset = response.context['formset']
# change the values in the underlying form
for form in enumerate(formset):
form.instance['something'] = i
# how do I post the formset back to myview? this does NOT work...
response = self.client.post("/myview", formset, follow=True)
AttributeError: 'MyFormSet' object has no attribute 'items'
这个错误完全有道理,因为我需要传递一个字典作为第二个参数,而不是 Formset。我希望 Formset 上有一些方法可以为我提供适当的字典(带有管理表单信息),但我一生都找不到它。
更新:
我这样做了:
data = {}
for field in formset.management_form:
data["-".join((formset.management_form.prefix, field.name))] = field.value()
for form in formset:
for field in form:
data["-".join((form.prefix, field.name))] = field.value()
self.client.post(reverse("/myview"), data, follow=True)
但我仍然想知道是否有内置的 formset 方法可以做到这一点,我只是看不到它....
【问题讨论】:
标签: django-testing