django template system, calling a function inside a model

crib picture crib · Aug 26, 2009 · Viewed 76.5k times · Source

I want to call a function from my model at a template such as:

class ChannelStatus(models.Model):
 ..............................
 ..............................

    def get_related_deltas(self,epk):
        mystring = ""
        if not self.get_error_code_delta(epk):
            return mystring
        else:
            for i in self.get_listof_outage():
                item = i.error_code.all()
                for x in item:
                    if epk == x.id:
                        mystring= mystring +" "+str(i.delta())
        return mystring         

And when I want to call this from the template: assume while rendering, I pass channel_status_list as

channel_status_list = ChannelStatus.objects.all()

{% for i in channel_status_list %}
  {{ i.get_related_deltas(3) }}
{% endfor %}

This doesn't work, I am able to call a function that consumes nothing, but couln't find what to do if it has parameter(s)

Cheers

Answer

Daniel Roseman picture Daniel Roseman · Aug 26, 2009

You can't call a function with parameters from the template. You can only do this in the view. Alternatively you could write a custom template filter, which might look like this:

@register.filter
def related_deltas(obj, epk):
    return obj.get_related_deltas(epk)

So now you can do this in the template:

{% for i in channel_status_list %}
  {{ i|related_deltas:3 }}
{% endfor %}