django - 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?
解决方案
推荐阅读
- c++ - C++ 访问外部类的静态字段 [获取错误 LNK2001]
- angular - Angular - 如何 MarkForCheck() ngfor 模板中的单个项目
- javascript - Map.On / Map.off MapboxGL JS
- regex - 用于替换除空白和指定目标之外的所有内容的正则表达式 Scala
- c# - 转换日期时间时,字符串未被识别为有效的日期时间
- python - 打开一个文本文件并创建一个字典变量
- ios - 无法在表视图内的集合视图上正确填充数组数据
- excel - 如何在数据库中上传时处理excel中的空白值还希望在excel中下载表而不在jsp中指定列名
- c++ - 没有初始化器的 constexpr 静态数据成员
- selenium - 如何为复选框选择定位器