Python和Django – 无法使用相对导入语句访问模块(已更新)

huangapple go评论56阅读模式
英文:

Python and Django - Cannot Reach Module With Relative Import Statement (UPDATED)

问题

我有一个名为views.py的文件,它从同一文件夹中存储的另一个文件中导入一个类。另一个文件名为models.py,需要导入的类名为Docgen。
我使用以下代码进行导入。

from .models import Docgen

但我一直收到以下错误。
ImportError: attempted relative import with no known parent package

在我写下from .models import Docgen这一行时没有显示错误,但出于某种原因它仍然无法工作,我无法弄清楚原因。由于某种原因,导入语句无法定位到models.py文件。

当我尝试在这个项目中的其他应用程序的views.py中从.models导入模块时,我也会收到相同的错误。这可能是在设置中某些东西被不小心更改了吗?

英文:

I have a file called views.py that imports a class from another file stored in the same folder. The other file is called models.py and the needed class is called Docgen.
I'm using the following code to import.

from .models import Docgen

But I keep getting the following error.
ImportError: attempted relative import with no known parent package

Python和Django – 无法使用相对导入语句访问模块(已更新)

No error is shown when I write the line from .models import Docgen but it still won't work for some reason I can't figure out. For some reason the import statement isn't able to locate the file models.py.

Python和Django – 无法使用相对导入语句访问模块(已更新)

I get the same error whenever I try to import a module from .models into views.py in other apps in this project as well. Could it be something in settings that has gotten changed somehow?

答案1

得分: 1

你可以尝试导入与当前目录相同的文件:

from . import models

然后将你的 "Docgen" 引用更改为 "models.Docgen"。

英文:

You may try importing files present in the same directory as

from . import models

then change your "Docgen" references to "models.Docgen"

答案2

得分: 1

你试过这个吗:

from your_base_directory.docgen.models import Docgen

我还会检查一下是否意外地删除了任何 init.py 文件?

英文:

Have you tried this:

from your_base_directory.docgen.models import Docgen

I would also check if any init.py was maybe accidentally removed?

huangapple
  • 本文由 发表于 2023年7月28日 01:06:08
  • 转载请务必保留本文链接:https://go.coder-hub.com/76782019.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定