My problem is similar to this thread: Can "list_display" in a Django ModelAdmin display attributes of ForeignKey fields?. I want to display a foreign key attribute from the list display. This attribute is a BooleanField. Normally, it would display a check or cross if the admin page is on the model itself containing the field. Such as this:
However when I reference this to other admin page.
class ProofOfPaymentAdmin(admin.ModelAdmin):
list_display = ('id', 'reference_number', 'user', 'is_subscribed',)
def is_subscribed(self, obj):
return obj.user.is_subscribed
The return from the list display is the boolean values True
or False
.
How can I change this to display the icons check or cross similar from the above?
Update 1: Result from first answer:
You can use format_html()
method to return HTML code for displaying the checkmark or cross icon based on the Boolean value, following is an example:
from django.utils.html import format_html
class ProofOfPaymentAdmin(admin.ModelAdmin):
list_display = ('id', 'reference_number', 'user', 'is_subscribed',)
def is_subscribed(self, obj):
if obj.user.is_subscribed:
return format_html('<span style="color:green">✔</span>')
else:
return format_html('<span style="color:red">✘</span>')
is_subscribed.short_description = 'Subscribed?' # Set the column header
This will display a green checkmark icon for True
values and a red cross icon for False
values. The format_html
method ensures that the HTML code is properly escaped to prevent any security vulnerabilities.