Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
139 views
in Technique[技术] by (71.8m points)

python - django template system, calling a function inside a model

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...