Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Django – how to show a mathematic result as percentage in dango admin

I have created a model that have one field that calculate the percentage of a month profit, the result is a float number rounded to 2 decimals, for example 0.50

I would like to have in the admin list as percentage, for example. 0.50 would show as 50.00%, is that possíble, how can i achieve that?

my model:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

class PortfolioToken(models.Model):
    total_today = models.FloatField()
    order_value = models.FloatField()
    token_price = models.FloatField()
    month_profit = models.FloatField(editable=False)

    def save(self, *args, **kwargs):
        if PortfolioToken.objects.exists():
            last = PortfolioToken.objects.latest('id')
            # month profit would show as percentage in admin
            self.month_profit = round((self.token_price - last.token_price)/last.token_price, 2)
        else
        ...
            

My admin list

class PortfolioTokenAdmin(admin.ModelAdmin):
    list_display =('total_today', 'order_value', 'token_price', 'month_profit')

>Solution :

You can add it as a custom field:

class PortfolioTokenAdmin(admin.ModelAdmin):
    fields = ('total_today', 'order_value', 'token_price', 'month_profit', 'percentage')
    readonly_fields = ('percentage',)

    def percentage(self, obj):
        # Return the month_profit as percentage string
        return str(format(float(obj.month_profit * 100), '.2f') + ' %')
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading