Adding Models to the Django Admin Interface

django admin include models
10 November 2024

Hello! Today we want to discuss how to add models to the Django Admin environment. Django is a popular framework for building powerful and flexible web applications. One of the interesting and useful features of Django is its administration panel. This panel allows us to easily manage our database models. So let's see how we can add our models to the management panel and benefit from this capability.

For your models to be accessible in the Django administration panel, you first need to register them in the admin.py file related to your application. This task is not a complicated process and can be accomplished with just a few lines of code. First, you need to include a file that contains the model definitions (usually models.py). Then you should import these models into the admin.py file and add them to the management class.

The management panel allows you to easily import, edit, and delete your data. You can also perform advanced filters and searches on your data. In this way, if you have launched your business with Django, you can use this tool for easier management of your information. Now, let's look at a real example to explore this topic.

For example, we have a simple model called Book that includes the information of books such as the title and author. We intend to add this model to the management panel so that we can easily manage its data. Here, we will review the necessary steps step by step.

Model Registration Code in the Management Interface

from django.contrib import admin
from .models import Book

class BookAdmin(admin.ModelAdmin):
list_display = ('title', 'author')

admin.site.register(Book, BookAdmin)

Line-by-Line Explanation of the Code:

from django.contrib import admin
This line is used to import the admin module from Django, which is necessary for managing models in the admin panel.

from .models import Book
Here, we import the Book model from the models.py file so we can add it to the management panel.

class BookAdmin(admin.ModelAdmin):
In this line, we define a class from the Admin model that allows us to display, edit, and manage the Book model.

list_display = ('title', 'author')
With this line, we determine which fields from the Book model will be displayed on the data list page in the management panel.

admin.site.register(Book, BookAdmin)
Finally, we register the Book model and the BookAdmin management class with the admin panel so that they can be utilized.

FAQ

?

How can I add models to the management panel?

?

Can I customize fields displayed in the management panel?

?

Can I display related models in the management panel?