I am trying to display different initial data for each form in my formset. I don't get an error, however the data is not being totally displayed. Only the first object shows up. How do I fix this?
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()]
When I run:
[print(form.initial) for form in formset]
I get:
{'name': <Name: John>}
{} # Where is my second object?
To solve this I used a list and appended dictionaries to it instead of using 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)
and instead of:
formset = MyFormSet(initial=[{'name': n for n in names} for names in all_names.values()]
I did:
formset = MyFormSet(initial=all_names)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.