Pre-populate an inline FormSet?

后端 未结 10 1544
自闭症患者
自闭症患者 2020-11-30 18:25

I\'m working on an attendance entry form for a band. My idea is to have a section of the form to enter event information for a performance or rehearsal. Here\'s the model

10条回答
  •  情歌与酒
    2020-11-30 19:14

    I'm having the same problem. I'm using Django 1.9, and I've tried the solution proposed by Simanas, overriding the property "empty_form", adding some default values in de dict initial. That worked but in my case I had 4 extra inline forms, 5 in total, and only one of the five forms was populated with the initial data.

    I've modified the code like this (see initial dict):

    class MyFormSet(forms.models.BaseInlineFormSet):
        model = MyModel
    
        @property
        def empty_form(self):
            initial = {'model_attr_name':'population_value'}
            if self.parent_obj:
                initial['name'] = self.parent_obj.default_child_name
            form = self.form(
                auto_id=self.auto_id,
                prefix=self.add_prefix('__prefix__'),
                empty_permitted=True, initial=initial
            )
            self.add_fields(form, None)
            return form    
    
    class MyModelInline(admin.StackedInline):
        model = MyModel
        formset = MyFormSet
    
        def get_formset(self, request, obj=None, **kwargs):    
            formset = super(HostsSpaceInline, self).get_formset(request, obj, **kwargs)
            formset.parent_obj = obj
            return formset
    

    If we find a way to make it work when having extra forms, this solution would be a good workaround.

提交回复
热议问题