2017-06-04 96 views
0

我是Django的新手(所以這可能是一個Python3問題)。另外,我還閱讀了其他類似的問題,例如Error importing Python moduleDjango:導入自定義Python3類的問題

我有以下結構的目錄:

-- 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() 

即一個類將其他人建造的。

使用從以前鏈接的問題

這會導致Django的服務器吐了這個錯誤solution

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

這讓我覺得定義一個類時,我沒有按照Python的約定,建在另一個類(但都在同一個目錄中)。

我做錯了什麼,我該如何解決?

+2

如果您嘗試從'.custom_class_1導入Custom_Class_1'(在'custom_class_1'前面有一個點表示相對導入),它會起作用嗎? – MSeifert

+0

Django錯誤消息沒有意義 - 它說'Custom_Class_1'是_module_。你確定這是實際的錯誤信息嗎? –

+0

@ MSeifert似乎工作! – SumNeuron

回答

1

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

from .custom_class_1 import Custom_Class_1 

.custom_class_1前告訴Python模塊custom_class_1應該從同一目錄中導入。

+0

因此,這是從'views.py'文件內工作的,但是我怎樣才能在'/ template/my_app/index.html'文件中做到這一點? – SumNeuron

+0

你能否問一個新問題並在其中包含相關文件(請隨時鏈接到評論中的新問題)?我不確定我可以在評論中回答這個問題(不知道你的文件)。 – MSeifert

+0

是的,這裏是https://stackoverflow.com/questions/44353505/django-import-custom-class-in-template-html-instead-of-view – SumNeuron

0

Django項目中的導入應該使用項目根目錄中的模塊路徑。 例如,如果my_class是在你的Django項目的根目錄, 那麼你就可以導入Custom_Class_2

from my_class.custom_class_2 import Custom_Class_2 

順便說一句,這是奇怪的名字Python模塊和類的名稱中「下課」。