现象
想创建一个新的app,报错内容如下:
PS D:\django\proj> python manage.py startapp appa
Traceback (most recent call last):
File "manage.py", line 21, in <module>
main()
File "manage.py", line 17, in main
execute_from_command_line(sys.argv)
File "D:\app\anaconda\lib\site-packages\django\core\management\__init__.py", line 381, in execute_from_command_line
utility.execute()
File "D:\app\anaconda\lib\site-packages\django\core\management\__init__.py", line 357, in execute
django.setup()
File "D:\app\anaconda\lib\site-packages\django\__init__.py", line 24, in setup
apps.populate(settings.INSTALLED_APPS)
File "D:\app\anaconda\lib\site-packages\django\apps\registry.py", line 91, in populate
app_config = AppConfig.create(entry)
File "D:\app\anaconda\lib\site-packages\django\apps\config.py", line 90, in create
module = import_module(entry)
File "D:\app\anaconda\lib\importlib\__init__.py", line 127, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 1006, in _gcd_import
File "<frozen importlib._bootstrap>", line 983, in _find_and_load
File "<frozen importlib._bootstrap>", line 965, in _find_and_load_unlocked
ModuleNotFoundError: No module named 'appa'
原因分析
粗一看很难看出是啥问题,报的不是manage.py的错,就是django源文件的错,这些肯定是没问题的,之前也成功创建过app。仔细看,发现中间有一个提示:
apps.populate(settings.INSTALLED_APPS)
这里提到了settings配置文件,检查一下,果然发现了问题。
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'appa',
'appb',
]
原来,我就打算创建appa和appb两个app,就先在INSTALLED_APPS里写进去了。
解决方案
拿掉INSTALLED_APPS配置里的appa试试看,把settings文件还原
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
再运行startapp
PS D:\python\django\proj> python manage.py startapp appa
PS D:\python\django\proj> python manage.py startapp appb
PS D:\python\django\proj>
没有报错了。