【问题标题】:How to use a property, in a django template, from a mongoengine model如何在 django 模板中使用来自 mongoengine 模型的属性
【发布时间】:2013-11-10 20:40:31
【问题描述】:

我在 Django 中使用 mongoengine。我有一个类 Noun,其他几个类(Person、Place、Event 等)从该类继承。 Noun 类如下所示:

class Noun(Document):
  label = StringField(max_length=120, required=True)
  contributor = StringField(max_length=120, required=True)
  description = StringField(required=False)
  @property
  def noun_cls():
      return self._cls
  meta = {'allow_inheritance': True}

当我尝试在模板中引用 noun_cls 属性时,我什么也得不到。例如:

{% for noun in Nouns %}
  <li>
        <a href="{{BASE_URL}}noun/update/{{ noun.id }}/{{ noun.noun_cls }}/">Edit {{ noun.noun_cls }}</a>
    <p>{{ noun.description }}</p>
  </li>
{% endfor %}

...这会产生类似“...noun/update/[long mongo id]//”的 url。就好像 noun_cls 属性被完全忽略了。对于先前存在的名词(或任何类型)以及在此代码更改后生成的新名词都是如此。有什么想法吗?

【问题讨论】:

  • 属性应该可以正常工作 - 只是没有 _cls 值。

标签: django mongodb django-models mongoengine


【解决方案1】:

def noun_cls() 更改为def noun_cls(self) 会起作用!

如果您使用的是 Django 模板引擎,它将忽略“不存在”的属性。

在您的情况下,您的def noun_cls() 缺少self,django 什么都不提供,而是引发异常。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-06-02
    • 2013-06-16
    • 1970-01-01
    • 2014-06-10
    • 1970-01-01
    • 2014-03-30
    • 1970-01-01
    • 2018-12-31
    相关资源
    最近更新 更多