Reputation: 6120
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 ...
Upvotes: 8
Views: 7345
Reputation: 727
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)
Upvotes: 0
Reputation: 6120
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.
Upvotes: 16
Reputation: 1034
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)
Upvotes: 7
Reputation: 1081
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] + '..')
Upvotes: 3