Search code examples
pythondjangodjango-modelsdjango-admindjango-modeladmin

Django list display of foreign key attribute that is boolean field using check or cross icons


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:

enter image description here

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.

enter image description here

How can I change this to display the icons check or cross similar from the above?

Update 1: Result from first answer:

enter image description here


Solution

  • 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">&#x2714;</span>') 
            else:
                return format_html('<span style="color:red">&#x2718;</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.