django-polymorphic icon indicating copy to clipboard operation
django-polymorphic copied to clipboard

Admin StackedPolymorphicInline: how to get instance value from inline child form?

Open drivelous opened this issue 3 years ago • 0 comments

This might be more django admin specific but figured I should add here. Hi there,

I need to conditionally render a form field field2 depending on the value of another field field1

# models.py
class Rule(models.Model):
    pass

class Action(PolymorphicModel):
    rule = models.ForeignKey(Rule)

class SpecificAction(Action):
    field1 = Boolean
    field2 = CharField

Usually, I'll do conditional rendering of a fields in the get_fields method and check the values of obj -- in example see HELP

# admin.py

class ActionInline(StackedPolymorphicInline):
    class SpecificActionInline(StackedPolymorphicInline.Child):
        model = SpecificActionInline

        def get_fields(self, request, obj=None):
             fields = super(ActionInline.SpecificActionInline, self).get_fields(request, obj)

             # HELP: this doesn't work because obj here refers to the `Rule` instance not `SpecificAction` instance
             if obj.field1 is False:
                 fields.remove('field2')
             return fields

         model = Action
         child_inlines = (SpecificActionInline,)


class RuleAdmin(PolymorphicInlineSupportMixin, admin.ModelAdmin):
    form = RuleForm
    inlines = (ActionInline,)

How would I get the SpecificAction instance in get_fields instead of the Rule instance?

Thank you in advance

drivelous avatar Feb 17 '22 20:02 drivelous