Enhancing Django Admin with Custom Column Display in Django
Mammadov
Posted on June 12, 2024
In Django’s admin interface, customizing how model fields are displayed can significantly improve the user experience. One way to achieve this is by defining functions that format model data in a more readable or useful way.
Take, for example, the initialled_name function. It’s designed to display a person’s name in an initialled format, which can be particularly handy when dealing with long lists of names where space is at a premium.
Here’s how it works:
def initialled_name(obj):
"""
Takes a model instance and returns the person's last name followed by their initials.
For instance, if obj.first_names='Jerome David' and obj.last_names='Salinger',
the output would be 'Salinger, J.D.'
"""
# Extract the first letter of each first name to create the initials
initials = '.'.join([name[0] for name in obj.first_names.split(' ') if name]) + '.'
# Format the last name and initials in a string
return f"{obj.last_names}, {initials}"
To integrate this into the Django admin, we use the list_display attribute of the ModelAdmin class. This attribute specifies which fields should be displayed on the change list page of the admin for a given model.
from django.contrib import admin
class ContributorAdmin(admin.ModelAdmin):
# Display the initialled name in the admin list view
list_display = (initialled_name,)
By adding initialled_name to list_display, we tell Django to call our function for each Contributor object in the list page. The function receives the object as its argument and returns the formatted name, which Django then displays in the corresponding column.
This customization not only adds a touch of elegance to the admin interface but also makes it easier to scan through records at a glance.
Source:
Web development with Django, Ben Shaw, Saurabh Badhwar, Chris Guest, Bharath Chandra K S
Posted on June 12, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.