dynamic initial data for Django model formsets

Here’s how you can pass initial values to a model formset (mfs) after the object was instantiated:

mfs.initial_extra = [
        'foo': 1,
        'bar': 'a',
        'foo': 2,
        'bar': 'b',
mfs.extra += len(mfs.initial_extra)
mfs.forms = [mfs._construct_form(i) for i in xrange(mfs.total_form_count())] # 'forms' is a cached property

Tested with Django-1.7 but should work with older versions. For regular formsets replace ‘initial_extra’ with ‘initial’.


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.