Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Displaying a DecimalField with currency in the django admin

I have multiple models with multiple DecimalField representing money, like 100.34 EUR.

My goal was to display the currency in the admin list view, like shown in this image.

http://i.imgur.com/XKEQFp9.png

However I couldn't find a way to do it for every money field.

I tried creating a custom MoneyField, inheriting from DecimalField and changind the unicode representation, but it didn't work.

I also tried with https://github.com/jakewins/django-money but I had no luck.

I investigated the source code of django admin and I finally found the problem:

In django.admin.contrib.admin.util.py in the display_for_field function it checks if the value is an instance of DecimalField. If that's the case it displays it like a Decimal number.

elif isinstance(field, models.DecimalField):
    return formats.number_format(value, field.decimal_places) 

It makes sense, but it prevents me from displaying the EUR symbol/text in the admin.

How can I solve this problem?

I know that I could simply use a method for each field that display the formatted value as a string, but I wanted to know if there was a DRYer way.

like image 690
Matteo Suppo Avatar asked Sep 12 '13 08:09

Matteo Suppo


1 Answers

For display in the admin list, you can make a custom function in your ModelAdmin class, which will be called to format each value:

class MyModelAdmin(admin.ModelAdmin):
    list_display = ('formatted_amount', ...other fields...,)

    def formatted_amount(self, obj):
        # obj is the Model instance

        # If your locale is properly set, try also:
        # locale.currency(obj.amount, grouping=True)
        return '%.2f EUR' % obj.amount
like image 199
augustomen Avatar answered Oct 23 '22 00:10

augustomen