【问题标题】:NameError in Django templateDjango模板中的NameError
【发布时间】:2014-07-04 12:46:53
【问题描述】:

我正在开发一个简单的 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

我真的不知道如何解决这个问题。

谢谢!

【问题讨论】:

    标签: python django python-3.x


    【解决方案1】:

    仅仅因为task 是您的应用程序的名称,就没有理由认为它会在任何特定模块中定义。 Python 的名称范围规则非常简单:除非在该模块中导入或分配,否则不会定义任何内容。如果您没有定义名称 task 的任何内容,则它仍然未定义。

    至于为什么你不能做from task.models import HabbitSource,你可能有循环依赖。如果rules 导入modelsmodels 导入rules,则在导入时无法解析依赖关系,因此会出现该错误。

    一种可能性是作弊并使用内部模型名称属性,它是一个字符串:

    if habbit._meta.object_name == 'HabbitSource':
    

    或者,您可以重新考虑您的架构:类型检查通常不是惯用的 Python,通常您只需适当地定义类的方法并调用它们。

    【讨论】:

      猜你喜欢
      • 2014-02-06
      • 1970-01-01
      • 2018-10-21
      • 2010-11-02
      • 2012-01-19
      • 2010-12-19
      • 2014-02-10
      • 2015-10-16
      • 2012-09-19
      相关资源
      最近更新 更多