0

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

dotty
  • 40,405
  • 66
  • 150
  • 195
  • Even where you can, you *should not*. The models should not have anything interesting to offer in terms of the presentation, nor should the presentation have any knowledge of the underlying models it presents. If you find that you need some functionality that crosses both the presentation and the business logic, it belongs in the *controller* (which in django, is the view function). – SingleNegationElimination Jun 14 '11 at 13:51

2 Answers2

2

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 }}
Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895
  • Would you recommend this way? If not why? – dotty Jun 14 '11 at 13:49
  • Yes, I don't see why not. As TokenMacGuy says, there's a distinction to be made between presentation and business logic, but I disagree with him that models can't have anything useful to say about presentation, and IMO this is a good example of a case when they do. – Daniel Roseman Jun 14 '11 at 14:11
0

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?

Community
  • 1
  • 1
Silver Light
  • 44,202
  • 36
  • 123
  • 164