开发者

Is it possible to perform model methods in a template?

I have a model which has a method called 'has_voted'. It looks like this...

def has_voted(self, user):
    # code to 开发者_StackOverflow社区find out if user is in a recordset, returns a boolean

Is it possible to perform this method inside a template? Something like object.has_vote(user)?


You can only call methods with no parameters. So {{ object.has_voted }} would be OK, if the method was defined simply as has_voted(self), but as you've shown it would not be.

The best way to pass a parameter to a method is to define a simple template filter.

@register.filter
def has_voted(obj, user):
    return self.has_voted(user)

and call it:

{{ object|has_voted:user }}


You can, but only if method has no parameters. Like this:

def has_voted(self):

{% if object.has_voted %}

If you method has parameters, you can't - this is Django religion.

See related question: How to use method parameters in a Django template?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜