【问题标题】:Django: issues with importing custom Python3 classDjango:导入自定义 Python3 类的问题
【发布时间】:2017-11-05 06:27:09
【问题描述】:

我是 Django 新手(所以这可能是一个 Python3 问题)。另外,我已经阅读了其他类似的问题,例如Error importing Python module

我有一个目录结构如下:

-- my_class

-- -- __init__.py

-- -- custom_class_1.py

-- -- custom_class_2.py

在文件 custom_class_2.py 的位置有以下几行:

from custom_class_1 import Custom_Class_1 
class Custom_Class_2:
    self.thing = Custom_Class_1()

即一个类是建立在其他类之上的。

使用先前链接问题中的solution

这会导致 Django 服务器吐出这个错误:

from custom_class_1 import Custom_Class_1
ImportError: No module named 'Custom_Class_1'

这让我觉得我在定义一个类时没有遵循 pythonic 约定,建立在另一个类上(但都在同一个目录中)。

我做错了什么以及如何解决?

【问题讨论】:

  • 试试from .custom_class_1 import Custom_Class_1是否有效(custom_class_1前面有一个点表示相对导入)。
  • 那个 Django 错误消息没有意义——它说Custom_Class_1 是一个模块。你确定那是实际的错误信息吗?
  • @MSeifert 似乎有效!!
  • @JohnGordon 是的,我确定。这就是终端在运行服务器时所写的内容,包括my_class

标签: python django python-3.x


【解决方案1】:

你可以使用relative import (see PEP 328 for more details):

from .custom_class_1 import Custom_Class_1

custom_class_1前面的.告诉Python模块custom_class_1应该从同一个目录导入。

【讨论】:

  • 所以这在views.py 文件中有效,但我如何在/template/my_app/index.html 文件中执行此操作?
  • 您能否提出一个新问题并在其中包含相关文件(请随时在 cmets 中链接到新问题)?我不确定我是否可以在评论中回答这个问题(不知道你的文件)。
【解决方案2】:

Django 项目中的导入应使用项目根目录中的模块路径。 例如,如果 my_class 位于 Django 项目的根目录下, 然后你可以导入Custom_Class_2

from my_class.custom_class_2 import Custom_Class_2

顺便说一句,在名称中使用“class”来命名 Python 模块和类是很奇怪的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-11-21
    • 1970-01-01
    • 2020-03-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-12
    • 2013-08-04
    相关资源
    最近更新 更多