Hiding extra field Django Admin

86 Views Asked by At

I want to display an extra field based on a boolean check associated with the model.

if obj.boolean:
  exclude(self.extra_field)

But the issue with this is that the extra field is not associated with the model so it is throwing error stating model does not contain this extra field.

The output that i am looking for is that, when this boolean is true the extra field should not get displayed in the model admin as well as model inline. But when it is false it should get displayed.

How can i achieve this?

1

There are 1 best solutions below

0
On

If that's only for display, you need to define a @property on your model which will return something depending on your boolean. Or you may define a method on an admin class like this:

def my_method(self, obj):
    # return some value depending on obj.boolean
    return ...

my_method.short_description = 'A label for my_method'

Than you may use it in admin's list_display list. I don't think you may completely remove field from list display for some entries and leave it for others (as it is table), but you may render it empty depending on your boolean.

For inlines you need to add this field into both fields and readonly_fields list to avoid Unknown field(s) error.

To display the field in detailed view, you need to add it to admin's readonly_fields.

In both ModelAdmin and InlineAdmin you may override get_readonly_fields method to return different fields-lists for different objects depending on your boolean.

Also, admin classes have get_fields method which is also overridable, but since your field is readonly you probably don't need it.

See ModelAdmin's options and methods for more details.