V
V
Vladimir Kuts2016-03-14 18:25:26
Django
Vladimir Kuts, 2016-03-14 18:25:26

Dynamic object edit form in Django admin?

Let's say I have a model (in fact, the model is much more complicated using mptt polymorphic tree):

class MyModel(models.Model):
     CHOICES = (
            (1, 'Type1'),
            (2, 'Type2')
     )
     my_type = models.Integerfield(choices=CHOICES)
     field1 =
     field2 = 
     field3 =
     field4 = 
    ....

How can I make it so that in the Django admin panel, when editing, say, an instance with my_type='Type1', only fields, say field1 and field2, are shown, and when editing an instance with my_type='Type2', only fields field4 and field5 are shown?
In essence, I need a form to be called with fields related to a specific type, and not a sheet with all possible fields.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
O
Oscar Django, 2016-03-15
@fox_12

class MyModelAdmin(admin.ModelAdmin):
    my_filter = {1: ('field1', 'field2'), 2: ('field3', 'field4')}
    def get_fields(self, request, obj=None):
        fields = super().get_fields(request, obj)
        if obj is None:
            return fields
        return [f for f in fields if f not in self.my_filter[obj.my_type]]

But this will only work when the object changes.
If you need it dynamically when creating, then there is only js, you catch the change in the my_type field and hide / show the necessary fields.
class MyModelAdmin(admin.ModelAdmin):
    class Media:
        js = (
            'js/my_fields_filter.js',
        )

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question