views:

1529

answers:

2

hello, 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

+9  A: 

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 %}
Daniel Roseman
hello, thanks alot for the backup! I am getting "related_deltas requires 1 arguments, 0 provided" error. I am doing exactly as you said.Regards
Hmm, that should work. Can you post the full traceback (probably somewhere like dpaste.com rather than here)?
Daniel Roseman
here it is: http://dpaste.com/85528/ ,thanks
That seems to be a different error, probably caused by a double pipe character in `{{ forloop.parentloop.counter0||add:"5" }}`.
Daniel Roseman
actually at my template, it is {{ forloop.parentloop.counter0|add:"5" }}, It is really weird it display it as "||".
I agree with Daniel, this does appear to be an issue with your template.
wlashell
A: 

Another option is to define a property. See http://adam.gomaa.us/blog/2008/aug/11/the-python-property-builtin/ .

You write your function that can do pretty much anything you want. You make it a read only property. You call the property from the template.

Et voilà !!!!

Arnaud Sahuguet