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?
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: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
andreadonly_fields
list to avoidUnknown field(s)
error.To display the field in detailed view, you need to add it to admin's
readonly_fields
.In both
ModelAdmin
andInlineAdmin
you may overrideget_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.