S
S
Stanislav Gordienko2015-12-15 04:17:35
Django
Stanislav Gordienko, 2015-12-15 04:17:35

How to hide model fields in the admin panel depending on the field value?

Hello everyone,
The question arose, is it possible to somehow hide the fields of the model, depending on the value of a particular field in the admin panel? For example, we have a model Machine. If the Color field contains the value "Red", then show two additional fields.
How can I do that?
Thank you.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander Lebedev, 2015-12-15
@stagor

For example, like this:

class BookAdmin(admin.ModelAdmin):
    list_display = ("pk", "get_title_or_nothing")

    def get_form(self, request, obj=None, **kwargs):
        if obj.type == "1":
            self.exclude = ("title", )
        form = super(BookAdmin, self).get_form(request, obj, **kwargs)
        return form

well, or with your subject area:
class CarAdmin(admin.ModelAdmin):
    list_display = ("pk", "model", "vin")

    def get_form(self, request, obj=None, **kwargs):
        if 'Red' not in obj.color:
            self.exclude = ("field1", "field2")
        form = super(CarAdmin, self).get_form(request, obj, **kwargs)
        return form

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question