(edit: Obsoleted nach Django 1.7+, nicht notwendig, mehr finden Sie Alasdair Antwort)
Ich denke, es geht um Sie feinere Kontrolle. Betrachten Sie den Code von contrib.admin.autodiscover
:
def autodiscover():
"""
Auto-discover INSTALLED_APPS admin.py modules and fail silently when
not present. This forces an import on them to register any admin bits they
may want.
"""
import copy
from django.conf import settings
from django.utils.importlib import import_module
from django.utils.module_loading import module_has_submodule
for app in settings.INSTALLED_APPS:
mod = import_module(app)
# Attempt to import the app's admin module.
try:
before_import_registry = copy.copy(site._registry)
import_module('%s.admin' % app)
except:
# Reset the model registry to the state before the last import as
# this import will have to reoccur on the next request and this
# could raise NotRegistered and AlreadyRegistered exceptions
# (see #8245).
site._registry = before_import_registry
# Decide whether to bubble up this error. If the app just
# doesn't have an admin module, we can ignore the error
# attempting to import it, otherwise we want it to bubble up.
if module_has_submodule(mod, 'admin'):
raise
So ist es automatisch die INSTALLED_APPS admin.py Module geladen werden kann und unbemerkt fehlschlagen, wenn sie nicht gefunden. Nun gibt es Fälle, wenn Sie tatsächlich wollen nicht, dass, wie wenn die eigene Verwendung AdminSite
:
# urls.py
from django.conf.urls import patterns, url, include
from myproject.admin import admin_site
urlpatterns = patterns('',
(r'^myadmin/', include(admin_site.urls)),
)
in diesem Fall Sie nicht autodiscovery()
anrufen müssen.
Es gibt auch andere Zeiten, wenn Sie nur eine Teilmenge der Apps Ihrer Projekte über Admin sehen oder bearbeiten möchten, und das Aufrufen von autodiscovery()
würde dies nicht ermöglichen.
Ich verstehe nicht, warum es Apps laden muss. Werden nicht jedes Mal Anwendungen in 'INSTALLED_APPS' geladen, wenn 'settings.py' ausgeführt wird (z. B. beim Starten des Servers)? – Bentley4
'autodiscover' lädt die Apps nicht, es wird' admin.py' für jede App importiert. – Alasdair
@ Bentley4 Ja wie Alasdair sagte, es importiert nur das 'admin.py' von jeder App. –