Sunday, October 17, 2021

Show custom Model data on admin page for rows

By default the object preview will be shown in the admin page after it registered.

Mostly the id, which is not human readable.

So we can add a custom format to display on  Admin page.


#in models.py

class Book(models.Model):

    ---

    ---

    def __str__(self):

        return self.title



This will show title as preview entry in the admin page.


In our admin page, we registered like this before.

admin.py

from django.contrib import admin

from .models import Book

admin.site.register(Book)


The above line will simply register the model and display as is described in models.py

To add more customization on admin page, use decorator insted of default register line.

admin.py

from django.contrib import admin

from .models import Book

@admin.register(Book)

class BookAdmin(admin.ModelAdmin):

  fields = ['title','description'] #what to show when opened the particular row,skips other entries

  list_display = ['title',description] #what to show on the table view

  list_filter = ['published']#right side filter section will be visible now to filter based on the fields

  search_fields = ['title','description']#top we have search field added


No comments:

Post a Comment