首页 > 解决方案 > 如何将 python 函数从另一个文件导入 django 视图

问题描述

我正在尝试从位于views.py 的django 项目目录之外的python 文件中调用一个函数。我尝试导入 python 文件,但运行 django 服务器时显示“没有名为 xxxx 的模块”。

树结构如下所示。

├── auto_flash
│ ├── __init__.py
│ └── test.py
└── 萤火虫
    ├── 检测报告
    │ ├── admin.py
    │ ├── admin.pyc
    │ ├── __init__.py
    │ ├── __init__.pyc
    │ ├── 迁移
    │ │ ├── __init__.py
    │ │ └── __init__.pyc
    │ ├── models.py
    │ ├── models.pyc
    │ ├── __pycache__
    │ │ └── __init__.cpython-35.pyc
    │ ├── 模板
    │ │ └── 检测报告
    │ │ └── home.html
    │ ├── tests.py
    │ ├── views.py
    │ └── views.pyc
    ├── 萤火虫
    │ ├── __init__.py
    │ ├── __init__.pyc
    │ ├── __pycache__
    │ │ ├── __init__.cpython-35.pyc
    │ │ └── settings.cpython-35.pyc
    │ ├── settings.py
    │ ├── settings.pyc
    │ ├── ui_cgi.py
    │ ├── urls.py
    │ ├── urls.pyc
    │ ├── wsgi.py
    │ └── wsgi.pyc
    ├── __init__.py
    └── 管理.py  

这里的项目名称是“fireflash”,该项目中有一个名为“detection_reports”的应用程序。还有另一个名为“auto_flash”的目录与“fireflash”具有相同的位置。我想要做的是从 detection_reports.views 中的“auto_flash”导入 test.py 文件并从视图中调用一个函数。像这样“从 auto_flash 导入测试”导入会引发错误“没有名为 auto_flash 的模块”。

标签: pythondjangodjango-views

解决方案


我已经尝试了上述所有解决方案,但更简洁的解决方案是附加 to 的路径,auto_flash问题syspath就解决了。感谢大家的努力。


推荐阅读