Code


Version 2 (modified by alekam, 4 years ago) (diff)

--

Admin change list view customization with ListColumn

Related ticket: #8054 Move method properties for admin list customisation to ModelAdmin

This ticket adds:

  • beatifull API to admin change list customization
  • ability to customize and localize 3rd-party application without fork it
  • ability to apply custom template filters on field value or model method returned value without any magic
  • ability to specify witch field will be used in order for column based on model method

ListColumn API

Arguments:

  • field_name - model field or model method name

Keyword arguments:

  • header - change list column header. If not provided standard algoritm to header column calculation will be used.
  • filter - template filters will be apllied to value on output.
  • load_filters - list of required template tags libraries. This libraries will be load before apply template filters to output value.
  • order_field - specify witch field will be used to prowide order by this column.
  • value_map - choices used to mapping display value

Example

Current way to admin change list view customization:

class Account(models.Model):
    foo = model.BooleanField(...)
    bar = model.CharField(...)
    baz = model.CharField(...)
    bonk = model.CharField(...)
    ends = models.DateTimeField()

    def get_bar_column(self):
        return ...
    get_bar_column.allow_tags = True

    def timeuntil_ends():
        return ...


class AccountAdmin(admin.ModelAdmin):
    list_display = ['foo', 'get_bar_column', 'baz', 'bonk', 'timeuntil_ends']

Proposed way:

class Account(models.Model):
    foo = model.BooleanField(...)
    bar = model.CharField(...)
    baz = model.CharField(...)
    bonk = model.CharField(...)
    ends = models.DateTimeField()

    def get_bar(self):
        return ...

class AccountAdmin(admin.ModelAdmin):
    list_display = [
        admin.ListColumn('foo', header='Foo Description', filter='boolean'),
        admin.ListColumn('get_bar', filter='safe', order_field='bar'),
        'baz',
        'bonk',
        admin.ListColumn('ends', filter='timeuntil', header="Ending in")
    ]