0

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

Nikko
  • 1,410
  • 1
  • 22
  • 49

1 Answers1

1

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.

Sunderam Dubey
  • 1
  • 11
  • 20
  • 40
  • Hi @Sunderam Dubey, your answer is correct, that may be the way. Although, I get the wrong icons . I updated the thread which shows the icons you provided. – Nikko Mar 14 '23 at 15:49
  • Upon digging in inspect the html. The icons came from staticfiles: `http://localhost:8000/static/admin/img/icon-yes.svg` – Nikko Mar 14 '23 at 15:53
  • @Nikko You can modify the icons according to yourself (maybe see bootstrap code), I have not much knowledge of icons, you can do it :) Do you also get a cross icon which you need? – Sunderam Dubey Mar 14 '23 at 15:58
  • @Nikko Do you want a red color cross icon? – Sunderam Dubey Mar 14 '23 at 16:00
  • I did got a red cross, but not the django staticfile default :) – Nikko Mar 14 '23 at 16:11