Django——多apps目录情况下的app注册

文章目录

多apps目录下的app注册

方式1-添加python导包路径

python 复制代码
import sys
sys.path.insert(0, str(BASE_DIR / "apps"))
print(sys.path)

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    # 直接写app名即可
    'home',
]
  • 原理:

原来的导包路径是直接在项目下开始:

将导包路径多添加一条:从apps文件夹下导入

方式2-修改AppConfig类名

settings.py

python 复制代码
INSTALLED_APPS = [
    # ...
    'luffycityapi.apps.home',
]

app下的apps.py

python 复制代码
from django.apps import AppConfig


class HomeConfig(AppConfig):
    default_auto_field = 'django.db.models.BigAutoField'
    name = 'project.apps.home'
  • 原理:

注册app时直接从项目下开始导入。

此时django在导入模块时,会找名为 project.apps.home 的app。

而尝试导入一个应用程序时,它会使用 AppConfig 的 name 属性作为模块的全名来查找和加载它,

所以就要修改AppConfig 的 name 属性

相关推荐
cup114 小时前
[技术复盘] Windows Python 打包实战:Nuitka 环境踩坑总结与 CI 自动化构建全指南
python·ai·环境变量·ci·nuitka·skill
aqi006 小时前
15天学会AI应用开发(七)有了大模型为什么还要引入RAG
人工智能·python·大模型·ai编程·ai应用
金銀銅鐵8 小时前
用 Python 实现 Take-Away 游戏
python·游戏
copyer_xyf9 小时前
Agent 流程编排
后端·python·agent
copyer_xyf9 小时前
Agent RAG
后端·python·agent
copyer_xyf10 小时前
【RAG】向量数据库:milvus
后端·python·agent
copyer_xyf10 小时前
Agent 记忆管理
后端·python·agent
星云穿梭1 天前
用Python写一个带图形界面的学生管理系统——完整教程
python
金銀銅鐵1 天前
用 Pygame 实现 15 puzzle
python·数学·游戏