Skip to content

Instantly share code, notes, and snippets.

@lc-thomas
Last active September 25, 2023 22:15
Show Gist options
  • Save lc-thomas/fa904e41f50e8741a574c4c04902c011 to your computer and use it in GitHub Desktop.
Save lc-thomas/fa904e41f50e8741a574c4c04902c011 to your computer and use it in GitHub Desktop.
Django custom admin site with list_display, tabular inline data, custom templates and custom view
from django.contrib import admin
from django.contrib.admin.models import LogEntry
from django.db.models import ManyToOneRel, ForeignKey, OneToOneField
from django.apps import apps
from django.contrib.auth.models import Group, User
from django.contrib.auth.admin import GroupAdmin, UserAdmin
from django.conf.urls import url
# admin custom views
from . import admin_views
# application models :
from .models import *
from app_base_data.models import *
class CustomAdminSite(admin.AdminSite):
site_header = "Ascension administrator site"
def get_urls(self):
base_admin_urls = super(CustomAdminSite, self).get_urls()
custom_urls = [
url(r'item_property_updater$', self.admin_view(admin_views.item_property_updater), name="preview"),
]
return base_admin_urls + custom_urls
admin.site = CustomAdminSite()
# register base admin models (groups and users)
admin.site.register(Group, GroupAdmin)
admin.site.register(User, UserAdmin)
# tabular inline recipes
class RecipeCostInline(admin.TabularInline):
model = RecipeCost
extra = 2 # how many rows to show
class RecipeAdmin(admin.ModelAdmin):
inlines = (RecipeCostInline,)
admin.site.register(Recipe, RecipeAdmin)
# tabular inline item categories and custom template
# list of templates that can be overriden :
# https://docs.djangoproject.com/en/2.1/ref/contrib/admin/#templates-which-may-be-overridden-per-app-or-model
# base templates :
# https://github.com/django/django/tree/master/django/contrib/admin/templates/admin
class ItemCategoryPropertyValueInline(admin.TabularInline):
model = ItemCategoryPropertyValue
extra = 2
class ItemAdmin(admin.ModelAdmin):
inlines = (ItemCategoryPropertyValueInline,)
change_list_template = 'admin/custom_item_change_list.html'
admin.site.register(Item, ItemAdmin)
# register every other models using list display :
ListAdmin = lambda model: type(model.__name__, (admin.ModelAdmin,), {
'list_display': [x.name for x in model._meta.fields],
'list_select_related': [x.name for x in model._meta.fields if isinstance(x, (ManyToOneRel, ForeignKey, OneToOneField,))]
})
# admin change logs
admin.site.register(LogEntry, ListAdmin(LogEntry))
# all application models that have not been registered yet
models = apps.get_models()
for model in models:
if model.__module__ in ['app.models', 'app_base_data.models']:
try:
admin.site.register(model, ListAdmin(model))
except admin.sites.AlreadyRegistered as e:
pass
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment