简体   繁体   中英

Django admin how to show a progress bar in percentage

在Django内置管理站点中,如何在“更改列表”页面和“更改表单”页面中将进度栏显示为字段?

For example:

  1. Create method percentage_paid in your model to calculate the result and render an HTML element.
# models.py

class SomeModel(models.Model):
    ....
    def percentage_paid(self):
        if self.paid_amount and self.final_price:
            percentage = round((self.paid_amount / self.final_price * 100), 2)
        else:
            percentage = 0
        return format_html(
            '''
            <progress value="{0}" max="100"></progress>
            <span style="font-weight:bold">{0}%</span>
            ''',
            percentage
        )
  1. Add this method field 'percentage_paid' to readonly_filds
  2. Meanwhile, add it to list_display if you want to show in Change List Page and or fields if want it in Change Form Page. I add it to fieldsets to customize my Change Form.
# admin.py

class CaseAdmin(CommonInfoAdmin):
    fieldsets = CommonInfoAdmin.fieldsets + (
        ('Sales Summary', {
            'fields': (
                ....
                ('final_price', 'paid_amount', 'balance', 'percentage_paid'),
                ....
            )
        }),
    )
    readonly_fields = [
        ....
        'percentage_paid',
    ]
    list_display = (
        ....
        'percentage_paid'
    )

The results:

  • Change List

更改列表

  • Change Form

变更表格

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM