Accessing parent model instance from modelform of admin inline

前端 未结 4 741
天命终不由人
天命终不由人 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:24

    Expanding on ilvar's answer a bit, If the form field of interest is constructed from a model field, you can use the following construction to apply custom behavior to it:

    class MyChildInline(admin.TabularInline):
        model = MyChildModel
        extra = 1
        def get_formset(self, request, parent=None, **kwargs):
            def formfield_callback(db_field):
                """
                Constructor of the formfield given the model field.
                """
                formfield = self.formfield_for_dbfield(db_field, request=request)
                if db_field.name == 'my_choice_field' and parent is not None:
                    formfield.choices = parent.get_choices()
                return formfield
            return super(MyChildInline, self).get_formset(
                request, obj=obj, formfield_callback=formfield_callback, **kwargs)
            return result
    

提交回复
热议问题