【问题标题】:django __unicode__() - how can i call this method in a templatedjango __unicode__() - 我如何在模板中调用此方法
【发布时间】:2010-12-31 03:40:04
【问题描述】:

我在我的联系人模型中定义了一个 unicode() 方法。

def __unicode__(self):
        return u'%s %s' % (self.first_name, self.last_name)

现在我想在模板中显示 unicode() 方法的返回值。

但我尝试的一切都失败了。

{{ object.unicode }}

{{ object.unicode() }}

{{ object.__unicode__ }}

{{ object.str }}

这让我很困惑,因为我有另一个模型级别的函数,可以毫无问题地从模板中引用。

这很好用:

def get_id(self):
        return "%i" % self.id 

{{ object.get_id|escape }}

【问题讨论】:

    标签: django-models django-templates


    【解决方案1】:
    {{ object }}
    

    将自动为任何对象返回__unicode__ 的值。

    【讨论】:

    • 太棒了。谢谢。这样可行。但是“(以及更多字符,所以 SO 不会抱怨)”是什么意思
    • SO 要求答案或评论至少包含 15 个字符。
    猜你喜欢
    • 2012-05-08
    • 1970-01-01
    • 2020-04-10
    • 2016-02-14
    • 1970-01-01
    • 2012-07-11
    • 1970-01-01
    • 1970-01-01
    • 2013-11-24
    相关资源
    最近更新 更多