问题描述
使用pycham创建Django 3.1.4项目时,第一次运行时,出现的错误。
Traceback (most recent call last):
File "/xxx/django3/manage.py", line 22, in <module>
main()
......
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/importlib/__init__.py", line 126, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 994, in _gcd_import
File "<frozen importlib._bootstrap>", line 971, in _find_and_load
File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 665, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 678, in exec_module
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
File "/xxx/django3/django3/settings.py", line 60, in <module>
'DIRS': [os.path.join(BASE_DIR, 'templates')]
NameError: name 'os' is not defined
原因分析
从报错内容可以看出,是settings.py中模版文件夹配置的问题。
使用Django2,settings文件中通常引入os包进行路径配置:
import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
......
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'templates')]
......
Django3中的写法有所改变,但TEMPLATES中写法不变,又没有导入os包,所以导致了错误:
from pathlib import Path
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
......
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'templates')]
......
解决办法
1. 修改写法(建议)
使用pathlib的Path,将代码改为:
’DIRS’: [Path(BASE_DIR, ‘templates’)]
python 3.4版本之后,支持路径管理库pathlib,代替os用于路径的处理
2. 导入os包
在配置文件开头导入OS
import os