Django admin.display colored_name in html

How can you add an html in django admin display?

from django.contrib import admin
from django.db import models
from django.utils.html import format_html

class Person(models.Model):
    first_name = models.CharField(max_length=50)
    last_name = models.CharField(max_length=50)
    color_code = models.CharField(max_length=6)

    @admin.display
    def colored_name(self):
        return format_html(
            '<span style="color: #{};">{} {}</span>',
            self.color_code,
            self.first_name,
            self.last_name,
        )

class PersonAdmin(admin.ModelAdmin):
    list_display = ('first_name', 'last_name', 'colored_name')
 
Test case in accounting. I need something like this to downlaod invoices from admin list view. 
 
 def docs_current(self, obj: Transaction) -> str: # Show files
docs = Document.objects.filter(transaction=obj)
urls = ""
for doc in docs:
urls = urls + doc.invoice.url
return urls 
 
 
Admin example to display urls.  


class TransactionAdmin(admin.ModelAdmin):
actions = [expenses, sales, waiting, internal]
search_fields = ('name', 'explanation', )
list_filter = ('transaction_type', 'paymentmethod', 'accounting_period__full_name', 'transaction_date', DocsCountFilter)
list_display = ('name', 'explanation', 'transaction_date', 'docs_count', 'docs_current')
inlines = [
DocumentInline,
]

def docs_count_current(self, obj: Transaction) -> str: # Only used to test count sync denormalisated
return str(Document.objects.filter(transaction=obj).count())

@admin.display
def docs_current(self, obj: Transaction) -> str:
docs = Document.objects.filter(transaction=obj)
urls = ""
for doc in docs:
urls = urls + doc.invoice.url + "<br />"
return format_html(urls)
 
 
 
 

 

Comments