Skip to content

AdminSite API Reference

The AdminSite class encapsulates an instance of the djadmin application. It manages model registration, URL routing, and provides a central access point for the admin interface.

Class Definition

from djadmin import AdminSite

class AdminSite:
    """
    An AdminSite object encapsulates an instance of the djadmin application,
    ready to be hooked into your URLconf.
    """

Constructor

def __init__(self, name='djadmin')

Parameters

  • name (str, optional): The site name used for URL namespacing. Default: 'djadmin'

Attributes Set

  • name (str): The site name (used as URL namespace)
  • site_header (str): Header text displayed in admin (default: '{name} Administration')
  • site_title (str): Title for admin pages (default: '{name} Admin')
  • index_title (str): Title for index/dashboard page (default: 'Site administration')

Example:

from djadmin import AdminSite

# Default site
site = AdminSite()
print(site.name)         # 'djadmin'
print(site.site_header)  # 'Djadmin Administration'

# Custom site
admin = AdminSite(name='myadmin')
print(admin.name)         # 'myadmin'
print(admin.site_header)  # 'Myadmin Administration'

# Customize text
admin.site_header = 'My Company Admin'
admin.site_title = 'Admin Portal'
admin.index_title = 'Dashboard'

Registration Methods

register()

def register(self, model_or_iterable, admin_class=None, override=False)

Register one or more models with an admin class.

Parameters

  • model_or_iterable (type | Iterable[type]): A model class or iterable of model classes
  • admin_class (type[ModelAdmin], optional): The admin class to use. Default: ModelAdmin
  • override (bool, optional): If True, replaces all existing registrations for the model. If False (default), adds to existing registrations.

Raises

  • No exceptions - silently allows multiple registrations for the same model

Examples

Single model registration:

from djadmin import AdminSite, ModelAdmin
from myapp.models import Product

site = AdminSite()

class ProductAdmin(ModelAdmin):
    list_display = ['name', 'price']

# Register with custom admin class
site.register(Product, ProductAdmin)

# Register with default ModelAdmin
site.register(Product)

Multiple models registration:

from myapp.models import Product, Category, Order

# Register multiple models with default admin
site.register([Product, Category, Order])

# Register multiple models with same admin class
class SimpleAdmin(ModelAdmin):
    list_display = ['__str__']

site.register([Product, Category], SimpleAdmin)

Override mode:

# First registration
site.register(Product, ProductAdmin)

# Add another registration (both will exist)
site.register(Product, AlternateProductAdmin)

# Override all previous registrations (only this one will exist)
site.register(Product, NewProductAdmin, override=True)

Notes

  • Multiple ModelAdmin classes can be registered for the same model
  • Each registration creates separate URLs and views
  • Useful for providing different admin interfaces for the same model
  • When using the @register decorator, use override=True in the decorator if needed

See also: @register decorator

unregister()

def unregister(self, model_or_iterable, admin_class=None)

Unregister one or more models.

Parameters

  • model_or_iterable (type | Iterable[type]): A model class or iterable of model classes
  • admin_class (type[ModelAdmin], optional): If provided, only unregister this specific admin class. If None, unregister all admin classes for the model.

Raises

  • ImproperlyConfigured: If the model is not registered

Examples

Unregister all admin classes for a model:

site.unregister(Product)  # Removes all Product registrations

Unregister specific admin class:

site.register(Product, ProductAdmin)
site.register(Product, AlternateProductAdmin)

# Remove only AlternateProductAdmin
site.unregister(Product, AlternateProductAdmin)

# ProductAdmin is still registered

Unregister multiple models:

site.unregister([Product, Category, Order])

Error handling:

try:
    site.unregister(UnregisteredModel)
except ImproperlyConfigured as e:
    print(f"Error: {e}")  # "The model UnregisteredModel is not registered."

is_registered()

def is_registered(self, model) -> bool

Check if a model is registered.

Parameters

  • model (type): The model class to check

Returns

  • bool: True if the model has at least one registered admin class, False otherwise

Example

site.register(Product, ProductAdmin)

print(site.is_registered(Product))   # True
print(site.is_registered(Category))  # False

get_model_admins()

def get_model_admins(self, model) -> list[ModelAdmin]

Get all admin classes registered for a model.

Parameters

  • model (type): The model class

Returns

  • list[ModelAdmin]: List of ModelAdmin instances (may be empty)

Example

site.register(Product, ProductAdmin)
site.register(Product, AlternateProductAdmin)

admins = site.get_model_admins(Product)
print(len(admins))  # 2

# Empty list if not registered
admins = site.get_model_admins(UnregisteredModel)
print(len(admins))  # 0

URL Methods

get_urls()

def get_urls() -> list[URLPattern]

Generate URL patterns for this admin site.

Returns

  • list[URLPattern]: List of Django URL patterns

URL Structure

The method generates URLs in this structure:

/                                      → index (project dashboard)
/{app_label}/                          → {app_label}_app_index (app dashboard)
/{app_label}/{model}/                  → {app}__{model}_list (ListView)
/{app_label}/{model}/__new__/          → {app}__{model}_add (CreateView)
/{app_label}/{model}/<int:pk>/{action}/  → record actions (e.g., /webshop/product/1/edit/)
/{app_label}/{model}/{action_bulk}/    → bulk actions (e.g., /webshop/product/delete_bulk/)

Example

from django.urls import path, include

site = AdminSite(name='admin')
site.register(Product, ProductAdmin)

# Manual URL inclusion
urlpatterns = [
    path('admin/', include(site.get_urls())),
]

# Or use the urls property (recommended)
urlpatterns = [
    path('admin/', include(site.urls)),
]

Notes

  • Called internally by the urls property
  • You typically don't call this directly - use site.urls instead
  • Automatically generates URLs for all registered models and their actions

urls

@property
def urls(self) -> tuple[list[URLPattern], str]

Return URL patterns for include() with namespace support.

Returns

  • tuple[list[URLPattern], str]: A 2-tuple (urlpatterns, app_name) for Django's include()

Example

Basic usage:

from django.urls import path, include
from djadmin import site

urlpatterns = [
    path('admin/', include(site.urls)),
]

With custom namespace:

from djadmin import AdminSite

custom_site = AdminSite(name='myadmin')
# ... register models ...

urlpatterns = [
    path('myadmin/', include(custom_site.urls)),
]

Multiple admin sites:

from djadmin import AdminSite

# Default admin for staff
staff_site = AdminSite(name='staff')
staff_site.site_header = 'Staff Portal'

# Separate admin for partners
partner_site = AdminSite(name='partners')
partner_site.site_header = 'Partner Portal'

urlpatterns = [
    path('staff/', include(staff_site.urls)),
    path('partners/', include(partner_site.urls)),
]

URL Namespace

The name parameter from the constructor becomes both the application namespace and instance namespace. This allows URL reversing:

from django.urls import reverse

site = AdminSite(name='admin')

# Reverse URLs with namespace
reverse('admin:index')                         # Dashboard
reverse('admin:webshop_product_list')          # Product list
reverse('admin:webshop_product_add')           # Add product
reverse('admin:webshop_product_edit', args=[1]) # Edit product #1

See also: URL Routing

reverse()

def reverse(self, viewname, kwargs=None, args=None) -> str

Reverse a URL within this admin site's namespace.

Parameters

  • viewname (str): View name without namespace prefix (e.g., 'index', 'webshop_product_list')
  • kwargs (dict, optional): URL kwargs (e.g., {'pk': 1})
  • args (tuple, optional): URL args (e.g., (1,))

Returns

  • str: The reversed URL path

Examples

Basic usage:

site = AdminSite(name='admin')

# Dashboard URL
url = site.reverse('index')
print(url)  # '/admin/'

# Model list URL
url = site.reverse('webshop_product_list')
print(url)  # '/admin/webshop/product/'

# Detail URL with pk
url = site.reverse('webshop_product_edit', kwargs={'pk': 42})
print(url)  # '/admin/webshop/product/42/edit/'

Comparison with Django's reverse():

from django.urls import reverse

# These are equivalent:
site.reverse('webshop_product_list')
reverse('admin:webshop_product_list')

# But site.reverse() is more convenient in admin code

In templates:

While this method is primarily for Python code, templates should use the url tag:

{% url 'admin:webshop_product_list' %}
{% url 'admin:webshop_product_edit' pk=object.pk %}

View Methods

index()

def index(self, request) -> HttpResponse

Project dashboard view showing all apps and models.

Parameters

  • request (HttpRequest): The HTTP request

Returns

  • HttpResponse: Rendered dashboard

Example

This method is called automatically by the URL routing. You don't typically call it directly:

# In urls.py
path('admin/', include(site.urls))

# Visiting /admin/ calls site.index(request)

Template

Uses djadmin/dashboard.html template with context:

  • apps - List of apps with their models
  • site_header - Site header text
  • site_title - Site title text
  • index_title - Index page title

app_index()

def app_index(self, request, app_label) -> HttpResponse

App dashboard view showing models for a specific app.

Parameters

  • request (HttpRequest): The HTTP request
  • app_label (str): The app label (e.g., 'webshop')

Returns

  • HttpResponse: Rendered app dashboard

Example

# In urls.py
path('admin/', include(site.urls))

# Visiting /admin/webshop/ calls site.app_index(request, app_label='webshop')

Template

Uses djadmin/app_dashboard.html template with context:

  • app_label - The app label
  • app_name - Human-readable app name
  • models - List of models in the app
  • site_header - Site header text

Site Configuration Attributes

These attributes can be customized to change the admin interface appearance:

site_header: str

Header text displayed at the top of admin pages.

Default: '{name.title()} Administration'

Example:

site = AdminSite(name='admin')
site.site_header = 'My Company Admin Portal'

site_title

site_title: str

Title used in browser title bar (HTML <title> tag).

Default: '{name.title()} Admin'

Example:

site = AdminSite(name='admin')
site.site_title = 'Admin Dashboard'

index_title

index_title: str

Title for the index/dashboard page.

Default: 'Site administration'

Example:

site = AdminSite(name='admin')
site.index_title = 'Control Panel'

Usage Examples

Basic Setup

# myproject/admin.py
from djadmin import AdminSite, ModelAdmin, register
from myapp.models import Product, Category

# Create custom site
site = AdminSite(name='admin')

# Register models
@register(Product, site=site)
class ProductAdmin(ModelAdmin):
    list_display = ['name', 'price']

@register(Category, site=site)
class CategoryAdmin(ModelAdmin):
    list_display = ['name']

# myproject/urls.py
from django.urls import path, include
from .admin import site

urlpatterns = [
    path('admin/', include(site.urls)),
]

Multiple Admin Sites

# myproject/admin.py
from djadmin import AdminSite, ModelAdmin
from myapp.models import Product

# Staff admin (full access)
staff_site = AdminSite(name='staff')
staff_site.site_header = 'Staff Portal'

class StaffProductAdmin(ModelAdmin):
    list_display = ['name', 'price', 'cost', 'profit']
    # ... full access configuration

staff_site.register(Product, StaffProductAdmin)

# Partner admin (limited access)
partner_site = AdminSite(name='partners')
partner_site.site_header = 'Partner Portal'

class PartnerProductAdmin(ModelAdmin):
    list_display = ['name', 'price']  # No cost/profit
    # ... limited access configuration

partner_site.register(Product, PartnerProductAdmin)

# myproject/urls.py
from django.urls import path, include
from .admin import staff_site, partner_site

urlpatterns = [
    path('staff/', include(staff_site.urls)),
    path('partners/', include(partner_site.urls)),
]

Custom Dashboard

from djadmin import AdminSite
from django.shortcuts import render

class CustomAdminSite(AdminSite):
    def index(self, request):
        """Custom dashboard with analytics"""
        context = self._get_base_context(request)

        # Add custom data
        context['total_products'] = Product.objects.count()
        context['recent_orders'] = Order.objects.order_by('-created_at')[:10]

        return render(request, 'myapp/dashboard.html', context)

site = CustomAdminSite(name='admin')

Programmatic Registration

from djadmin import AdminSite, ModelAdmin
from django.apps import apps

# Create site
site = AdminSite(name='admin')

# Auto-register all models in an app
for model in apps.get_app_config('myapp').get_models():
    if not site.is_registered(model):
        site.register(model)  # Uses default ModelAdmin

# Check registrations
for model in apps.get_app_config('myapp').get_models():
    if site.is_registered(model):
        admins = site.get_model_admins(model)
        print(f"{model.__name__}: {len(admins)} admin(s) registered")

Conditional Registration

from django.conf import settings

site = AdminSite(name='admin')

# Register with different admins based on settings
if settings.DEBUG:
    site.register(Product, DebugProductAdmin)
else:
    site.register(Product, ProductAdmin)

Default Admin Site

django-admin-deux provides a default admin site instance for convenience:

from djadmin import site

# This is equivalent to:
# site = AdminSite(name='djadmin')

Usage with default site:

from djadmin import site, register, ModelAdmin
from myapp.models import Product

# Using decorator with default site
@register(Product)
class ProductAdmin(ModelAdmin):
    list_display = ['name', 'price']

# In urls.py
from django.urls import path, include
from djadmin import site

urlpatterns = [
    path('admin/', include(site.urls)),
]

See Also