Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django admin: Format fields in list, but keep sortable?

I keep numeric fields like "size", "width", "height" in my database. Now I would attach units like "KiB" or "pixels" to them when showing them in the change list. This could easily be achieved by adding callables such as "size_formatted" etc to list_display. However, these are no longer sortable.

Is there a way around this limitation?

like image 277
Sam Avatar asked Dec 02 '09 20:12

Sam


People also ask

How do I sort fields in Django admin?

You can order the fields as you wish using the ModelAdmin. fields option. The order of fields would depend on the order in which you declare them in your models. So alternatively you could order the fields in the way you would want them to show in the admin.

How do you make a field non editable in Django admin?

editable=False will make the field disappear from all forms including admin and ModelForm i.e., it can not be edited using any form.

What is Django admin for?

Overview. The Django admin application can use your models to automatically build a site area that you can use to create, view, update, and delete records. This can save you a lot of time during development, making it very easy to test your models and get a feel for whether you have the right data.


1 Answers

Read here - ModelAdmin.list_display (read a lot to get to the point ;) )

you need to add admin_order_field attribute to your function

class YourAdminCLass(admin.ModelAdmin)
   [...]
   def size_formatted(self, obj):
          return "whatever you need"
   size_formatted.admin_order_field = 'size'
like image 170
Pydev UA Avatar answered Oct 06 '22 19:10

Pydev UA