Django-admin
1.启动
django启动后,会加载settings中的install_apps
INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'app01.apps.App01Config', 'rest_framework', 'corsheaders' ]
from django.contrib import admin
admin.py: from django.contrib.admin.sites import AdminSite, site from django.utils.module_loading import autodiscover_modules def autodiscover(): autodiscover_modules('admin', register_to=site) # 加载每一个app下的admin.py文件
2. 注册
admin会对注册的每个模型表添加增删改查四个url
admin.site.register(Book) class BookConfig(admin.ModelAdmin): pass admin.site.register(Book, BookConfig)
sites中有register方法
def register(self, model_or_iterable, admin_class=None, **options): admin_class = admin_class or ModelAdmin
如果没有传进自定义的BookConfig类,默认用ModelAdmin
class AdminSite(object): def __init__(self): self._register = {} def register(self, model, admin_class=None): admin_class = admin_class or ModelAdmin self._registry[model] = admin_class(model, self) site = AdminSite()
执行每一个app下的admin.py文件
from django.contrib import admin admin.site.register(Book, BookConfig) admin.site.register(Publish)
3.设计url
格式: path中的函数部分为一个元组,里面第一个参数是列表,第二个和第三个是None
urlpatterns = [ path('admin/', admin.site.urls), path('test/', ([ path('index/', views.index), ], None, None)) ]
model._meta.model_name: 模型表的名称
model._meta.app_label :模型表所在的app的名称
django在启动的过程中,会自动加载每一个app下的apps文件,apps文件中的app名_config类有一个ready方法,会自动执行
1.启动
from django.apps import AppConfig from django.utils.module_loading import autodiscover_modules class StarkConfig(AppConfig): name = 'stark' def ready(self): autodiscover_modules("stark")
2. 注册
class AdminSite(object): def __init__(self): self._registry = {} def register(self, model, admin_class=None): if not admin_class: admin_class = ModelAdmin self._registry[model] = admin_class(model, self)
3. 设计url