【问题标题】:Django admin: how to display number with fixed length?Django admin:如何显示固定长度的数字?
【发布时间】:2022-01-16 02:07:05
【问题描述】:

这是我的模型:

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'

admin.py

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

对于amount=2800print(self.df_amount()) 给出$ 2,800.00$ 2,800.00 显示在管理面板中,中间的空格被截断为一个空格,与预期不符。

所以我的问题是如何在管理面板中保留字符串中间的空格?谢谢!

【问题讨论】:

    标签: django django-admin


    【解决方案1】:

    你可以使用format_html(...)函数,

    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(" ", " ")}')

    【讨论】:

    • 感谢您的回答!顺便说一句,  被读取为 html,因此实际上没有出现。请将& 替换为&
    猜你喜欢
    • 2011-12-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-09
    • 1970-01-01
    • 2020-01-14
    相关资源
    最近更新 更多