How to add custom column in the Django Admin change list view?

How to add custom column in the Django Admin change list view?

Add custom column in the Django Admin change list view

Note: If you want to read the blog series on Django Admin customization, then click here.

Suppose you have a Book model which has an author field as given below.

# app_name/models.py

class Book(models.Model):
    ...
    author = models.ForeignKey(User, on_delete=models.CASCADE)

And you want to show the author's email in the list view of Book model admin, here is how you do it.

# app_name/admin.py

from django.contrib import admin
from app_name.models import Book

@admin.register(Book)
class BookAdmin(admin.ModelAdmin):
    ...
    list_display = ("author_email", ) # author_email value is coming from below

    def author_email(self, obj): # You can create a custom method and show it in the 'list_display'
        return obj.author.email

Any thoughts? Write it down in the comments.

For more such crispy blogs daily, follow Dev.Junction, subscribe to our newsletter and get notified.