djang的ModuleNotFoundError

2024-07-05 12:10:09 发布

您现在位置:Python中文网/ 问答频道 /正文

我想在视图上下文中使用其他python文件的一些功能。在myapp中,我创建了一个名为“code”的文件夹,在这个文件夹中我有一个名为“code”的文件示例e.py". 我试着像这样进口视图.py: 视图.py公司名称:

from django.shortcuts import render
from django.views import View
# Create your views here.
import sys
sys.path.append('./code')
import examplee as expl
class CmtGraphTool(View):
    def get(self, request, *args, **kwargs):
        list = expl.test1()
        context = {list}
        return render(request, "cmtgraphtool.html", context)

以及示例e.py包含一个返回元素列表的简单函数。问题是,当我试图在视图中导入和使用test1函数时,Spyder(我的开发环境)可以看到这个函数,但是当我尝试用python运行django服务器时管理.py运行服务器时,会引发一个错误:

ModuleNotFoundError:没有名为“Example”的模块

如何以django可以看到的方式包含来自其他文件的函数? 谢谢;)


Tags: 文件django函数frompyimport文件夹view
1条回答
网友
1楼 · 发布于 2024-07-05 12:10:09

如果它在一个文件夹中,并且在app目录中,请确保代码文件夹中有一个空白的__init__.py文件

那就试试这个

from django.shortcuts import render
from django.views import View
# Create your views here.
from .code import examplee as expl
class CmtGraphTool(View):
    def get(self, request, *args, **kwargs):
        list = expl.test1()
        context = {list}
        return render(request, "cmtgraphtool.html", context)

相关问题 更多 >