Why isn't admin.autodiscover() called automatically in Django when using the admin, why was it designed to be called explicitly?

后端 未结 3 494
旧时难觅i
旧时难觅i 2021-02-05 17:14

Without putting admin.autodiscover() in urls.py the admin page shows You don\'t have permission to edit anything (See SO thread).

Why is this

3条回答
  •  长发绾君心
    2021-02-05 17:40

    (edit: Obsoleted after Django 1.7+, not necessary more, see Alasdair's answer)

    I think it's about giving you finer control. Consider the code of 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 it will automatically load the INSTALLED_APPS admin.py modules and fail silently when not found. Now, there are cases when you actually don't want that such as when using your own 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 this case, you don't need to call autodiscovery().

    There are also other times when you only want to see or edit a subset of apps of your projects through admin, and calling autodiscovery() would not enable you to do that.

提交回复
热议问题