Generic Django Admin Class for All Models

Posted on Feb 23, 2023

Django provides a great admin interface that allows you to manage your models in a convenient way. However, if you have many models in your project, creating separate admin classes for each model can be a time-consuming task. In this blog post, we will show you how to create a generic Django admin class that you can use for all models in your project.

The generic admin class that we are going to create will display all the fields of the model except the id field. This is because the id field is added automatically by Django and it’s not necessary to display it in the admin interface.

Here’s the code for the generic admin class:

from django.contrib import admin
from .models import Model1, Model2, Model3

class GenericModelAdminClass(admin.ModelAdmin):
    def get_list_display(self, request):
        all_fields = [field.name for field in self.model._meta.fields if field.name != "id"]
        return all_fields

admin.site.register(Model1, GenericModelAdminClass)
admin.site.register(Model2, GenericModelAdminClass)
admin.site.register(Model3, GenericModelAdminClass)

As you can see, we import the required models at the top of the file. Then we define a new class called GenericModelAdminClass that inherits from admin.ModelAdmin.

Inside the class, we define a method called get_list_display. This method is responsible for returning a list of field names that should be displayed in the admin interface. In our case, we use a list comprehension to loop through all the fields of the model and add their names to a list, except for the id field.

Finally, we register the models with the admin site using the admin.site.register method and pass in the model class and the GenericModelAdminClass class.

Now, when you access the admin interface for any of the registered models, you will see all the fields of the model except the id field. This saves you from having to create separate admin classes for each model.

In conclusion, creating a generic Django admin class can save you a lot of time if you have many models in your project. By following the steps outlined in this blog post, you can easily create a generic admin class that you can use for all models in your project.