django __unicode __() - 如何在模板中调用此方法

时间:2009-12-30 15:53:05

标签: django-models django-templates

我在Contact模型中定义了一个 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 }}

1 个答案:

答案 0 :(得分:13)

{{ object }}

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

相关问题