Accessing parent model instance from modelform of admin inline

前端 未结 4 768
天命终不由人
天命终不由人 2020-12-24 07:59

I\'m using a TabularInline in Django\'s admin, configured to show one extra blank form.

class MyChildInline(admin.TabularInline):
    model = MyChildModel
           


        
4条回答
  •  鱼传尺愫
    2020-12-24 08:39

    I'm using Django 1.10 and it works for me:
    Create a FormSet and put the parent object into kwargs:

    class MyFormSet(BaseInlineFormSet):
    
        def get_form_kwargs(self, index):
            kwargs = super(MyFormSet, self).get_form_kwargs(index)
            kwargs.update({'parent': self.instance})
            return kwargs
    

    Create a Form and pop an atribute before super called

    class MyForm(forms.ModelForm):
    
        def __init__(self, *args, **kwargs):
            parent = kwargs.pop('parent')
            super(MyForm, self).__init__(*args, **kwargs)
            # do whatever you need to with parent
    

    Put that in the inline admin:

    class MyModelInline(admin.StackedInline):
        model = MyModel
        fields = ('my_fields', )
        form = MyFrom
        formset = MyFormSet
    

提交回复
热议问题