【发布时间】:2014-05-22 17:43:25
【问题描述】:
我从其他文件导入函数时遇到问题。
我有文件 forms.py 和 helpers.py
我的 helpers.py:
from .forms import *
def check_pesel(pesel):
sum, ct = 0, [1, 3, 7, 9, 1, 3, 7, 9, 1, 3, 1]
for i in range(11):
sum += (int(pesel[i]) * ct[i])
return (str(sum)[-1] == '0')
def check_nip(nip_str):
nip_str = nip_str.replace('-', '')
if len(nip_str) != 10 or not nip_str.isdigit():
return False
digits = map(int, nip_str)
weights = (6, 5, 7, 2, 3, 4, 5, 6, 7)
check_sum = sum(map(mul, digits[0:9], weights)) % 11
return check_sum == digits[9]
和forms.py:
from .helpers import *
#(...) rest of code
当我尝试在 forms.py 中使用 check_pesel() 时,我得到:
global name 'check_pesel' is not defined
当我从 .helpers import check_pesel, check_nip 更改时,我得到:
无法导入名称 check_nip
我该如何解决这个问题?
【问题讨论】:
-
你有一个循环导入!这就是你得到那个错误的原因。尝试循环导入时,这是一个标准的 Python 错误
-
您必须将
.forms导入您的helpers.py模块吗?如果您可以在不破坏模块的情况下删除它,这将解决您的错误。 -
在 helpers.py 中我导入了几乎所有内容(模型、表单等),所以在 views.py(在 django 中)我只能导入那个文件。但是,在 forms.py 中我需要访问模型,这就是我导入 helpers.py 的原因。任何建议如何改变它?
-
不幸的是没有。这是您必须在整个 django 应用程序中重做的架构更改。循环依赖有很多方法可以解决,但是您没有显示整个代码,因此我们可以为您提供帮助。不幸的是,我多次遇到同样的问题,不得不重新排列很多代码。
标签: python django python-2.7 python-import