django admin truncate text in list_display
Asked Answered
D

4

8

Need to trunate text in admin list_display

Have the following in admin model but still shows full text.

from django.template.defaultfilters import truncatewords

def get_description(self, obj):
    return truncatewords(obj.description, 10)
get_description.short_description = "description"

class DieTaskAdmin(admin.ModelAdmin):
    list_display =['severity','priority', 'subject', 'status','created',get_description.short_description']

admin.site.register(DieTask, DieTaskAdmin)

i.e original text of description field contains more than 255 char. I like to only display the first 10 char plus ...

Demography answered 27/10, 2016 at 3:27 Comment(0)
D
16

I had to create a property in the model as shown here:

from django.template.defaultfilters import truncatechars
...

@property
def short_description(self):
    return truncatechars(self.description, 35)

And use the short_descriptioin in the admin to trim the text.

Demography answered 27/10, 2016 at 3:48 Comment(0)
L
7

how about using python inbuilt slice syntax

class DieTaskAdmin(admin.ModelAdmin):
    list_display =['severity','priority', 'subject', 'status','created','get_description']
    def get_description(self, obj):
        return obj.description[:10]
    get_description.short_description = "description"

admin.site.register(DieTask, DieTaskAdmin)
Lir answered 7/6, 2020 at 17:8 Comment(1)
This is a great solution. I would also let anyone know who uses this that .short_description is the actual field here to put as the column head so that your column now doesn't just show as 'get_description'.Malherbe
P
3

Personally I would avoid using Django template functions inside model methods/properties. IMO is cleaner solution use native Python method instead:

@property
def short_description(self):
    return self.description if len(self.description) < 35 else (self.description[:33] + '..')
Prying answered 19/12, 2018 at 12:45 Comment(0)
C
0

Django version: 4.2.3

from django.template.defaultfilters import truncatechars


class DieTaskAdmin(admin.ModelAdmin):
    list_display =['severity', 'priority', 'subject', 'status','created', 'short_description']
    
    def short_description(self, obj: DieTask) -> str:
        return truncatechars(obj.description, 10)

admin.site.register(DieTask, DieTaskAdmin)
Cyna answered 4/8, 2024 at 21:4 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.