How to Create a List Display for a Database Table in Admin in Django 


               


How to Create a List Display for a Database Table in Admin in Django



Python


In this article, we show how to create a list display for a database table (a model) in admin in Django.

So if you create a database table in Django and simply register it in admin with the line, admin.site.register(database_table_name), by default, in admin, when you click on the database table, it will just show the database table objects.

So if you created a database table called BlogComments, it will show BlogComment object, BlogComment object, if you have 2 objects.

If you defined a __str__ method for the database table, it will show whatever you specified in that method.

However, we can do something else in Django.

We can create a list display in Django. Instead of just having the object name appear when we click on a database, we can create a list display (or list view) of various fields of the database table.

So let's give an example of this.

Let's go ahead and create the following database table called Book, shown in the code below.





So we create a database table called Book that has the fields, title, author, description, and publicationyear.

So now we just have to make makemigrations and migrate in the command prompt of our computer, so that all changes are reflected throughout the website.

Then obviously, we must go into the admin.py file of the app that we created the database table and make some updates.

In order to show a database table in admin with Django, we have the register the database table (the model) in the admin.py file. Also, because we're creating a custom admin view, we create an admin table in the admin.py file.

All of this is shown in the code below.



So this is what we've done in this code.

We create a database table that is an admin table. So it's just like a regular database table, except that it is only seen by admin. It is only seen by the user who is logged in as the admin.

So in this ModelAdmin, we specify, list_display and set it equal to ('title', 'author', 'description', 'publicationyear')

These are the fields that will show when we click the database table on the home page of the Django admin page.

Instead of just seeing the table name followed by objects, such as Book object, we now see a list display of the fields that we specified.

So I went ahead and entered in a book into the database table. I then clicked on the database table on the admin home page and got the following, shown below.

Django admin list display of database table

So you can see above the list display of the database table instead of just seeing objects or whatever you defined in the __str__ method in the database table.

This is how you can create a list display for a database table in admin in Django.


Related Resources

How to Randomly Select From or Shuffle a List in Python



HTML Comment Box is loading comments...