我正在尝试为表单集中的每个表单显示不同的初始数据。我没有收到错误,但是数据并未完全显示。仅显示第一个对象。我该如何解决?
all_names = defaultdict(list)
for object in MyModel.objects.all(): # obj1 = John, obj2 = Bob
all_names['name'].append(object)
MyFormSet = modelformset_factory(MyModel, fields=('name'), extra=2)
formset = MyFormSet(initial=[{'name': n for n in names} for names in all_names.values()]
当我跑步时:
[print(form.initial) for form in formset]
我得到:
{'name': <Name: John>}
{} # Where is my second object?
答案 0 :(得分:0)
为解决这个问题,我使用了一个列表并附加了字典,而不是使用defaultdict
all_names = list() # used a list instead of defaultdict
for object in MyModel.objects.all(): # obj1 = John, obj2 = Bob
d = dict()
d['name'] = object
all_names.append(d)
,而不是:
formset = MyFormSet(initial=[{'name': n for n in names} for names in all_names.values()]
我做到了:
formset = MyFormSet(initial=all_names)