Skip to content

Instantly share code, notes, and snippets.

@webtk
Created July 28, 2018 06:10
Show Gist options
  • Save webtk/3e7aa15bc20c4f16d8215a3f245ca0e7 to your computer and use it in GitHub Desktop.
Save webtk/3e7aa15bc20c4f16d8215a3f245ca0e7 to your computer and use it in GitHub Desktop.
Python Django Admin Auto Register Model Simply
from django.contrib import admin
from django.contrib.admin.sites import AlreadyRegistered
def load_fields(model):
field_list = [f.name for f in model._meta.get_fields() if f.auto_created == False]
return field_list
def auto_register(model):
# Get all fields from model, but exclude autocreated reverse relations
field_list = load_fields(model)
# Dynamically create ModelAdmin class and register it.
klass_name = "%sAdmin" % model.__name__
my_admin = type(klass_name, (admin.ModelAdmin,), {'list_display': field_list})
try:
admin.site.register(model, my_admin)
except AlreadyRegistered:
# This model is already registered
pass
models = apps.get_app_config('YOUR_APP').models.values()
module = __import__("YOUR_APP.admin_class")
admin_module = getattr(module, 'admin_class')
for model in models:
class_name = "%sAdmin" % model.__name__
try:
admin_class = getattr(admin_module, class_name)
admin.site.register(model, admin_class)
except AttributeError:
auto_register(model)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment