首页 > 解决方案 > Django custom AppConfig breaks the project

问题描述

I've got a bare-bones demonstration Django project created with Django 2.2. The structure looks like:

my_project/
├── db.sqlite3
├── my_app
│   ├── admin.py
│   ├── apps.py
│   ├── __init__.py
│   ├── models.py
│   ├── urls.py
│   └── views.py
├── manage.py
├── my_project
│   ├── settings.py
│   ├── urls.py
│   └── wsgi.py
└── requirements.txt

This started as a tiny issue: "my_app" was showing up in the Django admin as "MY_APP" (with an underscore). The Django docs say that you can make this prettier by defining a custom app config that subclasses "django.apps.AppConfig", and that typically this subclass would be defined in (using my example) "my_app/apps.py". In fact, using manage.py startapp my_app even generates this for you:

# my_app/apps.py
from django.apps import AppConfig


class MyAppConfig(AppConfig):
    name = 'my_app'

The docs also say to "put the dotted path to that subclass in INSTALLED_APPS". Another approach is to set the default_app_config variable in your app's "__init__.py", but that "New applications should avoid default_app_config. Instead they should require the dotted path to the appropriate AppConfig subclass to be configured explicitly in INSTALLED_APPS."

However, if I do add the path to the custom app config into INSTALLED_APPS like this:

# settings.py
...
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'my_app',
    'my_app.apps.MyAppConfig'                                                                                                                                                                            
]
...

the project immediately crashes with "LookupError: No installed app with label 'admin'."

The error traces back to the reference to admin.site.urls in the project's root "urls.py" (line 6 below):

from django.contrib import admin
from django.urls import include, path

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

In conclusion, adding the path to the "apps" module created by "startapp" -- even without making any changes to that module -- crashes the project. OTOH if I go against the docs' advice and define default_app_config in "my_app/init.py", that does work.

This seems very basic, but Googling it is turning up nothing, which usually means I'm making some fundamental error that I don't realize. Any ideas, anyone?

标签: djangodjango-admindjango-apps

解决方案


推荐阅读