[Django]-Passing initial into Django's ModelFormSet

10πŸ‘

You are passing an empty queryset to ModelFormset.

ExampleModelFormSet = modelformset_factory(ExampleModel, extra=2)
formset = ExampleModelFormSet(queryset=ExampleModel.objects.none(),
                          initial=[{'name': 'Some Name'},
                                   {'name': 'Another Name'}])

which is indeed the way to achieve what you want. It makes sense to 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, you can override the Formset.

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

Note: initial is list of dicts. Its desirable to have items in list exactly equal to the number of extra.

πŸ‘€simplyharsh

9πŸ‘

New in Django 1.4 …if you set initial on a modelformset it now only applies to the β€˜extra’ forms, not those bound to instances from the queryset:

https://docs.djangoproject.com/en/dev/topics/forms/modelforms/#providing-initial-values

So the various hacks above are no longer necessary and using initial is the answer.

πŸ‘€Anentropic

6πŸ‘

The best way I’ve found to do this is to just manually adjust the formset object’s β€œextra” attribute after initialization. This has been tested and works in Django 1.9.

ExampleModelFormSet = modelformset_factory(ExampleModel, extra=1)
formset = ExampleModelFormSet(initial=[{'name': 'Some Name'},
                                       {'name': 'Another Name'}])
formset.extra = 3

This will spit out 3 forms (2 prepopulated and 1 blank).

If you want something more dynamic (e.g. initial is a var calculated somewhere else), you can do something like this:

ExampleModelFormSet = modelformset_factory(ExampleModel, extra=1)
formset = ExampleModelFormSet(initial=initial)
formset.extra += len(initial)

Hope that helps.

πŸ‘€Chad

4πŸ‘

It is still possible to pass initial to a ModelFormSet.

from django.forms.models import modelformset_factory
from example.models import ExampleModel

ExampleModelFormSet = modelformset_factory(ExampleModel)
formset = ExampleModelFormSet(initial=[{'name': 'Some Name'},
                                       {'name': 'Another Name'}])

If this is not what your after, can you explain your question more.

EDIT:

ExampleModelFormSet = modelformset_factory(ExampleModel, extra=2)
formset = ExampleModelFormSet(queryset=ExampleModel.objects.none(),
                              initial=[{'name': 'Some Name'},
                                       {'name': 'Another Name'}])
πŸ‘€Gerry

1πŸ‘

In Django 1.4 the rule changed: the number of initials to be displayed corresponds to β€œextra” parameter.
https://docs.djangoproject.com/en/dev/topics/forms/modelforms/#providing-initial-values

In my case the count of initial parameters varies dynamically, so
I found the following way:

initial=[{'name': 'Some Name'},{'name': 'Another Name'}]
formset = ExampleModelFormSet(queryset=ExampleModel.objects.none(),
                      initial=initial, extra=len(initial))


class MyBaseFormSet(BaseModelFormSet):
    def __init__(self, *args, **kwargs):
        self.extra = kwargs.pop('extra', self.extra)
        super(MyBaseFormSet, self).__init__(*args, **kwargs)

provided, ExampleModelFormSet is based on MyBaseFormSet

πŸ‘€igo

0πŸ‘

A simple solution could be that you pass a form that extends a modelform() to a formset (rather than modelformset).

That way you can set initial values in the form.

πŸ‘€lprsd

0πŸ‘

I think you can use initial argument, as with regular formsets
http://docs.djangoproject.com/en/dev/topics/forms/formsets/#using-initial-data-with-a-formset

0πŸ‘

You can alter the initial data afterwards.

For example:

# Construct the FormSet class
ExampleFormSet = modelformset_factory(ParentModel, ChildModel)

# Set the initial data
initial_data = {'field1': 1}
for form in ExampleFormSet.extra_forms:
    for field in form.fields:
        field.initial = initial_data[field.name]
πŸ‘€vdboor

0πŸ‘

The simple way how to pass initial data with the same count of extra forms:

MyModelFormSet = lambda *a, **kw: modelformset_factory(MyModel, extra=kw.pop('extra', 1))(*a, **kw)

Usage in views:

initial=[{'name': 'Some Name'},{'name': 'Another Name'}
formset = MyModelFormSet(queryset=MyModel.objects.none(), initial, extra=len(initial))})
πŸ‘€Alex Isayko

0πŸ‘

Affter two days found this: http://streamhacker.com/2010/03/01/django-model-formsets/

def custom_field_callback(field):
    return field.formfield(required=False)

FormSet = modelformset_factory(model, formfield_callback=custom_field_callback)

def custom_field_callback(field):
    if field.name == 'optional':
        return field.formfield(required=False)
    elif field.name == 'text':
        return field.formfield(widget=Textarea)
    elif field.name == 'integer':
        return IntegerField()
    else:
        return field.formfield()
πŸ‘€Stefan

Leave a comment