调整子应用保存目录以后导致django无法识别子应用的BUG
问题:有时因为我们调整了子应用保存目录之后,子应用注册会导致系统找不到该子应用而报错。
解决:因为我们调整子应用保存目录以后导致django无法识别子应用的BUG。
只需要把apps设置为系统识别的导包路径即可。
# 只需要把apps设置为系统识别的导包路径即可。
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__)))
# 把网站子应用所在目录设置为了导包路径
# sys.path就是导包路径,就是python能够自动导包的地方:只要你在这个列表当中记录了这个路径,它里面的模块都会被全局加载到
# print(sys.path) __> ['/home/moluo/Desktop/xxx/xxxapi', '/home/moluo/Desktop/xxx/xxxapi', '/opt/pycharm-2019.2.4/helpers/pycharm_display', '/home/moluo/.virtualenvs/xxx/lib/python36.zip', '/home/moluo/.virtualenvs/xxx/lib/python3.6', '/home/moluo/.virtualenvs/xxx/lib/python3.6/lib-dynload', '/usr/lib/python3.6', '/home/moluo/.virtualenvs/xxx/lib/python3.6/site-packages', '/opt/pycharm-2019.2.4/helpers/pycharm_matplotlib_backend']['/home/moluo/Desktop/xxx/xxxapi', '/home/moluo/Desktop/xxx/xxxapi', '/opt/pycharm-2019.2.4/helpers/pycharm_display', '/home/moluo/.virtualenvs/xxx/lib/python36.zip', '/home/moluo/.virtualenvs/xxx/lib/python3.6', '/home/moluo/.virtualenvs/xxx/lib/python3.6/lib-dynload', '/usr/lib/python3.6', '/home/moluo/.virtualenvs/xxx/lib/python3.6/site-packages', '/opt/pycharm-2019.2.4/helpers/pycharm_matplotlib_backend']
# 鉴于上面的sys.path的打印结果,如果我们写成 sys.path.insert(0,'/home/moluo/Desktop/renran/renranapi/renranapi/apps')也是可以的,但是不够灵活,所以改成下面的代码
import sys
sys.path.insert(0,os.path.join(BASE_DIR, "apps"))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '%=l9-5s0i26qxcvxcvx9df4$l@x(34qey)n3b'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
...
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'corsheaders',
'users',
]
# ...后面省略