Skip to content

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

@drivelous

Description

@drivelous

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions