dotty
dotty

Reputation: 41433

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 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)?

Upvotes: 0

Views: 125

Answers (2)

Silver Light
Silver Light

Reputation: 45902

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?

Upvotes: 0

Daniel Roseman
Daniel Roseman

Reputation: 599470

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 }}

Upvotes: 2

Related Questions