13

无需admin.autodiscover()输入 urls.py 即可显示管理页面You don't have permission to edit anything请参阅 SO 线程)。

为什么会这样?如果您总是需要admin.autodiscover()使用管理员添加编辑信息,即使您有超级用户名和密码以确保安全,为什么 Django 开发人员不admin.autodiscover()自动触发?

4

3 回答 3

18

在 Django 1.7 之前,建议将admin.autodiscover()调用放在 urls.py 中。这允许它在必要时被禁用。要求admin.autodiscover()而不是自动调用它是 Python 哲学“显式优于隐式”的一个例子。请记住,该django.contrib.admin应用程序是可选的,它并非安装在每个站点上,因此始终运行自动发现是没有意义的。

大多数情况下,自动发现工作得很好。但是,如果您需要更多控制权,您可以手动导入特定应用的管理文件。例如,您可能希望注册多个管理站点,每个站点具有不同的应用程序。

应用程序加载在 Django 1.7 中进行了重构。autodiscover()移至管理应用程序的默认应用程序配置。这意味着自动发现现在在加载管理应用程序时运行,无需添加admin.autodiscover()到您的 urls.py。如果您不想要自动发现,现在可以使用 禁用它SimpleAdminConfig

于 2012-10-09T20:10:43.997 回答
14

(编辑:在 Django 1.7+ 之后已过时,不需要更多,请参阅 Alasdair 的回答)

我认为这是为了给你更好的控制。考虑以下代码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

所以它会自动加载 INSTALLED_APPS admin.py 模块并在找不到时静默失败。现在,有些情况下您实际上不希望这样,例如使用自己的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)),
)

在这种情况下,您不需要调用autodiscovery().

还有其他时候,您只想通过管理员查看或编辑项目的一部分应用程序,而调用autodiscovery()不会让您这样做。

于 2012-10-09T21:09:15.247 回答
4

Django 不需要你使用 django。每个站点上的contrib .admin - 它不是核心模块。

于 2012-10-10T00:48:45.537 回答