django template call function

2019-04-12 14:43发布

Using google appengine and django.

Whenever I have a db.ReferenceProperty() inside a model like:

class User( db.Model ) :
    name = db.StringProperty()
    avatar = db.ReferenceProperty( dbImage )

So when putting out a User's page, in the django template I CAN'T do

<div>
    <span>{{ user.name }}</span>
    <span>{{ user.avatar.key() }}</span>
</div>

What I'm doing right now is writing a bit of python code before the data goes out to the template that looks like

user.avatarsKey = user.avatar.key()

Then

<div>
    <span>{{ user.name }}</span>
    <span>{{ user.avatarsKey }}</span>
</div>

eliminating the function call. I don't like this though, because I have to do it in a lot of places and its starting to get cluttery. Is there a way to invoke the .key() method of a db object from inside the template?

1条回答
Deceive 欺骗
2楼-- · 2019-04-12 15:16

In django templates, function invocation is just function getting. in your example, try:

{{ user.avatar.key }}

I know, it's weird. But hey, it's even worse with arrays/lists:

{{ user.mylist.0 }}
查看更多
登录 后发表回答