Home > Software design >  Django admin: how to display number with fixed length?
Django admin: how to display number with fixed length?

Time:12-12

This is my model:

from django.contrib.humanize.templatetags.humanize import intcomma


class Flow(models.Model):
    amount = models.DecimalField(max_digits=10, decimal_places=2)
    
    def df_amount(self):
        return '{intcomma(abs(self.amount)):>12}'
    df_amount.admin_order_field = 'amount'
    df_amount.short_description = 'amount'

In admin.py,

@admin.register(Flow)
class FlowAdmin(admin.ModelAdmin):
    list_display = (
        'df_amount',
    )

For amount=2800, print(self.df_amount()) gives $ 2,800.00 but $ 2,800.00 is displayed in the admin panel where the spaces in the middle were truncated to only one space, not as expected.

So my question is how to reserve the spaces in the middle of the string in admin panel? Thank you!

CodePudding user response:

You can use the format_html(...) function,

from django.utils.html import format_html


@admin.register(Flow)
class FlowAdmin(admin.ModelAdmin):
    list_display = (
        'df_amount',
    )

    def df_amount(self, instance):
        return format_html(f'$ {instance.df_amount().replace(" ", " ")}')
  • Related