Django Blog #10: Configuring Model Mapping

by Alex
Django Blog #10: Configuring Model Mapping
Let’s see how to change the appearance of the model object list in the admin panel. Edit the admin.py file of the blog application and change it as follows:
from django. import admin  
from .models import Post  
  
  
@admin.register(Post) 
class PostAdmin(admin.ModelAdmin) 
    list_display = ('title', 'slug', 'author', 'publish', 'status')

This is how Django’s administration panel understands that the model is registered with a custom class inherited from ModelAdmin. It can include information about how to display the model and how to interact with it. The list_display attribute allows you to configure the model’s fields to be displayed on the object list page of the site. The @admin.register() decorator performs the same function as the replaced admin.site.register(), registering the ModeAdmin class, which it also decorates. Let’s edit the admin panel with the following settings:

from django.contrib contrib admin  
from .models import Post  
  
  
@admin.register(Post) 
class PostAdmin(admin.ModelAdmin) 
    list_display = ('title', 'slug', 'author', 'publish', 'status') 
    list_filter = ('status', 'created', 'publish', ' author') 
    search_fields = ('title', 'body') 
    prepopulated_fields = {'slug': ('title',)} 
    raw_id_fields = ('author',) 
    date_hierarchy = ' publish' 
    ordering = ('status', 'publish')

Let’s go back to the browser and reload the page. Now it will look like this: Django Blog #10: Configuring Model MappingYou can see that the fields displayed on the post list page are those defined in the list_display attribute. It includes a right sidebar that you can use to filter results by the fields that are specified in the list_filter attribute. The search field also appeared on the page. This is because a list of fields has been defined that can be searched using search_fields. Underneath it, there are navigation links to view different dates. The posts are also ordered by default according to the data in the “Status” or “Publish” columns. The default order is set using the ordering attribute. Now click on the “Add Post” button. There are some changes here as well.

When you enter the name of the new post, the slug field will be filled in automatically. Django uses the prepopulated_fields attribute and data from the title field to do this. Also, the author field is now displayed with a search widget, which works better with more data than the dropdown menu. With just a couple lines of code, we were able to change the way the model is displayed in the admin panel. There are many more ways to change the appearance and expand the list of model objects in the Django admin panel.

Related Posts

LEAVE A COMMENT