Register all models with Django admin


Sometimes, mostly when throwing together a quick idea or MVP, it can be useful to just register all models with the admin and leave proper customization for later.

This snippet achieves exactly that:

from django.apps import apps
from django.contrib import admin


class ListAllFieldsAdminMixin:
    def __init__(self, model, admin_site):
        self.list_display = [field.name for field in model._meta.fields]
        super(ListAdminMixin, self).__init__(model, admin_site)

models = apps.get_app_config("<app_name>").get_models()

for model in models:
    admin_cls = type("AdminClass", (ListAllFieldsAdminMixin, admin.ModelAdmin), {})
    try:
        admin.site.register(model, admin_cls)
    except admin.sites.AlreadyRegistered:
        pass  # This just means we probably have a proper admin for the class already defined

See also