django模板系统,在模型中调用函数 [英] django template system, calling a function inside a model

查看:185
本文介绍了django模板系统,在模型中调用函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从模型中调用一个函数,例如:

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

def get_related_deltas(self,epk):
mystring =
如果不是自己。 get_error_code_delta(epk):
return mystring
else:
for i in self.get_listof_outage():
item = i.error_code.all()
for x in项目:
如果epk == x.id:
mystring = mystring ++ str(i.delta())
返回mystring

当我想从模板中调用它时:
假设在渲染时,我将channel_status_list作为

  channel_status_list = ChannelStatus.objects.all()

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

这不起作用,我可以调用一个没有任何东西的函数,但是如果它有参数,那么couln没有找到该怎么办p>

Cheers

解决方案

您不能调用具有参数的函数模板。您只能在视图中执行此操作。或者,您可以编写自定义模板过滤器,可能如下所示:

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

所以现在你可以在模板中:

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


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

解决方案

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

这篇关于django模板系统,在模型中调用函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆