I wrote this admin class to change the way objects instances are being displayed on my…
- User
I wrote this admin class to change the way objects instances are being displayed on my django admin dashboard.
Code: class ProfileAdmin(admin.ModelAdmin): model = Profile list_display = ('user', 'bio', 'location', 'birth_date')
how do I set character limit on the bio field.
Assistant
In Django Admin, the
list_displayfields are rendered as-is by default, so if you want to limit the number of characters shown for a field likebio, you need to define a custom method in yourModelAdminclass and use that method inlist_display.Here's how you can do it:
✅ Updated Code with Character Limit on
bio:from django.utils.html import format_html from django.utils.text import Truncator class ProfileAdmin(admin.ModelAdmin): model = Profile list_display = ('user', 'limited_bio', 'location', 'birth_date') # replaced 'bio' with 'limited_bio' def limited_bio(self, obj): return Truncator(obj.bio).chars(100) # limits to 100 characters, adds '...' if truncated limited_bio.short_description = 'Bio' # sets column header name
🔍 Explanation:
Truncatorfromdjango.utils.textis a utility that safely truncates text..chars(100)ensures that up to 100 characters are displayed, and it appends an ellipsis (...) if the text was truncated.- You can also use
.words(20)instead of.chars(100)if you'd prefer truncation based on word count.
🧪 Optional: Preserve HTML in Bio (if needed)
If
biocontains HTML (e.g., from a rich text editor), and you want to preserve it without escaping:def limited_bio(self, obj): return format_html(Truncator(obj.bio).chars(100))⚠️ Be cautious when using
format_html— make sure the content is safe or sanitized to avoid XSS vulnerabilities.
Let me know if you also want to apply this kind of truncation in the actual model detail view (i.e., the object change form)!
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.