django forms: editing multiple sets of related objects in a single form

前端 未结 3 453
天涯浪人
天涯浪人 2020-12-29 15:30

I\'m trying to do something that should be very common: add/edit a bunch of related models in a single form. For example:

Visitor Details:
Select destination         


        
3条回答
  •  一生所求
    2020-12-29 15:37

    So, as you've seen, one of the things about inlineformset_factory is that it expects two models - a parent, and child, which has a foreign key relationship to the parent. How do you pass extra data on the fly to the form, for extra data in the intermediary model?

    How I do this is by using curry:

    from django.utils.functional import curry
    
    from my_app.models import ParentModel, ChildModel, SomeOtherModel
    
    def some_view(request, child_id, extra_object_id):
        instance = ChildModel.objects.get(pk=child_id)
        some_extra_model = SomeOtherModel.objects.get(pk=extra_object_id)
    
        MyFormset = inlineformset_factory(ParentModel, ChildModel, form=ChildModelForm)
    
        #This is where the object "some_extra_model" gets passed to each form via the
        #static method
        MyFormset.form = staticmethod(curry(ChildModelForm,
            some_extra_model=some_extra_model))
    
        formset = MyFormset(request.POST or None, request.FILES or None,
            queryset=SomeObject.objects.filter(something=something), instance=instance)
    

    The form class "ChildModelForm" would need to have an init override that adds the "some_extra_model" object from the arguments:

    def ChildModelForm(forms.ModelForm):
        class Meta:
            model = ChildModel
    
        def __init__(self, some_extra_model, *args, **kwargs):
            super(ChildModelForm, self).__init__(*args, **kwargs)
            #do something with "some_extra_model" here
    

    Hope that helps get you on the right track.

提交回复
热议问题