Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set instance of each form in Django model formset

Tags:

python

django

When working with Django model forms, I often do something like this:

def my_view(request):
    new_entry = MyModel(name='a')
    form = MyModelForm(instance=new_entry)
    ...

I want to do something similar with a modelformset. Something like this would be ideal:

def my_view(request):
    MyFormSet = modelformset_factory(MyModel, form=MyModelForm)
    new_entries = [MyModel(name='a'), MyModel(name='b')]
    formset = MyFormSet(instances=new_entries) # off course this does not work
    ...

Since the items are not stored in the database yet, I can't set the instances using a queryset. If I want to use initial I have to declare the fields in the form, which is not ideal and seems a bit hacky.

Any suggestions how I can set the instances of each modelform in a modelformset?

like image 462
Kritz Avatar asked Apr 28 '16 13:04

Kritz


People also ask

What is inline formset in django?

Django formset allows you to edit a collection of the same forms on the same page. It basically allows you to bulk edit a collection of objects at the same time.

What is form Is_valid () in django?

The is_valid() method is used to perform validation for each field of the form, it is defined in Django Form class. It returns True if data is valid and place all data into a cleaned_data attribute.


1 Answers

Ok, I think I've found a solution.

class FormSetWithInstances(BaseFormSet):
    def __init__(self, *args, **kwargs):
        self.instances = kwargs.pop('instances')
        super(FormSetWithInstances, self).__init__(*args, **kwargs)

    def get_form_kwargs(self, index):
        form_kwargs = super(FormSetWithInstances, self).get_form_kwargs(index)
        if index < len(self.instances):
            form_kwargs['instance'] = self.instances[index]
        return form_kwargs

Be careful when using this modelformsets or inlinemodelformsets, as the queryset will override the instance you set.

like image 101
Kritz Avatar answered Oct 30 '22 20:10

Kritz