我正在开发一个简单的Django项目。但是,我对python和Django不太熟悉。它不断抛出“ NameError”。
在我的模板中,代码如下所示:
{% for habbit_source in habbit_source_list %}
<span class="habbit-hide">{{habbit_source.get_tomato_achieve}}</span>
...
{% endfor %}
get_tomato_achieve
是Model类的函数:task.models.HabbitSource
,其定义如下:
def get_tomato_achieve(self):
return rules.get_achieve_tomato(self)
在中rules.py
,我想判断输入参数的类型get_tomato_achieve(habbit)
,但是我是否使用
if type(habbit) == task.models.HabbitSource:
或者
if isinstance(habbit, task.models.HabbitSource):
它将抛出NameError: Name task is not defined.
(当然是定义的。这是我的应用程序的名称。)
如果我写from task.models import HabbitSource
,它会丢的ImportError: cannot import HabbitSource
。
我真的不知道该怎么解决。
谢谢!
仅仅是因为它task
是应用程序的名称,所以没有理由认为它将在任何特定模块中定义。Python的名称范围规则非常简单:除非在模块中导入或分配,否则什么都不会定义。如果您没有定义该名称的任何内容task
,那么它将保持未定义状态。
至于为什么不能做from task.models import HabbitSource
,您可能有循环依赖。如果使用rules
importmodels
和models
import rules
,则在导入时无法解决依赖关系,因此会出现该错误。
一种可能是作弊并使用内部模型名称属性,该属性是一个字符串:
if habbit._meta.object_name == 'HabbitSource':
或者,您可以重新考虑您的体系结构:类型检查通常不是惯用的Python,通常您只需要适当地定义类的方法并调用它们即可。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句