Pre-populate an inline FormSet?

后端 未结 10 1533
自闭症患者
自闭症患者 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:17

    Using django 1.7 we ran into some issues creating an inline form with additional context baked into the model (not just an instance of the model to be passed in).

    I came up with a different solution for injecting data into the ModelForm being passed in to the form set. Because in python you can dynamically create classes, instead of trying to pass in data directly through the form's constructor, the class can be built by a method with whatever parameters you want passed in. Then when the class is instantiated it has access to the method's parameters.

    def build_my_model_form(extra_data):
        return class MyModelForm(forms.ModelForm):
            def __init__(self, *args, **kwargs):
                super(MyModelForm, self).__init__(args, kwargs)
                # perform any setup requiring extra_data here
    
            class Meta:
                model = MyModel
                # define widgets here
    

    Then the call to the inline formset factory would look like this:

    inlineformset_factory(ParentModel, 
                          MyModel, 
                          form=build_my_model_form(extra_data))
    

提交回复
热议问题