You passing an empty queryset to ModelFormset, i guess.
ExampleModelFormSet = modelformset_factory(ExampleModel, extra=2)
formset = ExampleModelFormSet(queryset=ExampleModel.objects.none(),
initial=[{'name': 'Some Name'},
{'name': 'Another Name'}])
This indeed is a way to do what you want to do. It makes sense when you pass an empty queryset. Else, initial values will override the model's database value.
And if I suppose, you are passing a non-empty queryset, and yet want your extra forms to be filled will initial values, overriding can be the option.
from django.forms.models import modelformset_factory
ExampleFormset = modelformset_factory(OpenIDProfile, extra=3)
class myFormset(ExampleFormset):
def _construct_form(self, i, **kwargs):
"""
Instantiates and returns the i-th form instance in a formset.
"""
if self.is_bound and i < self.initial_form_count():
pk_key = "%s-%s" % (self.add_prefix(i), self.model._meta.pk.name)
pk = self.data[pk_key]
pk_field = self.model._meta.pk
pk = pk_field.get_db_prep_lookup('exact', pk)
if isinstance(pk, list):
pk = pk[0]
kwargs['instance'] = self._existing_object(pk)
if i < self.initial_form_count() and not kwargs.get('instance'):
kwargs['instance'] = self.get_queryset()[i]
defaults = {'auto_id': self.auto_id, 'prefix': self.add_prefix(i)}
if self.data or self.files:
defaults['data'] = self.data
defaults['files'] = self.files
# Check to confirm we are not overwriting the database value.
if not i in range(self.initial_form_count()) and self.initial:
try:
defaults['initial'] = self.initial[i - self.initial_form_count()]
except IndexError:
pass
# Allow extra forms to be empty.
if i >= self.initial_form_count():
defaults['empty_permitted'] = True
defaults.update(kwargs)
form = self.form(**defaults)
self.add_fields(form, i)
return form
initial
is list of dicts. Its desirable to have items in list exactly equal to the number of extra.