django模板系统,在模型中调用函数

时间:2023-01-17 00:00:09

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

干杯

5 个解决方案

#1


77  

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

#2


30  

If the method doesn't require any arguments, you can use the @property decorator and access it normally in the template.

如果该方法不需要任何参数,您可以使用@property decorator,并在模板中正常地访问它。

class ChannelStatus(models.Model):
    ...
    @property
    def function_you_want_as_property(self):
        mystring = ""
        ...

#3


3  

If you find that there are too many properties running around everywhere or you have a template filter for every other method that you write, another solution was suggested on IRC thanks @FunkyBob. It's a little well, erm, funky but it is nice in certain cases.

如果您发现到处都有太多的属性,或者您为编写的每个其他方法都有一个模板过滤器,那么在IRC上提出了另一种解决方案,感谢@FunkyBob。这有点好,嗯,很时髦,但在某些情况下很不错。

  class MethodProxy(object):
        """For consolidating into 1 method the calling of methods with various single args
        (suitable dictionary keys)

        class MyModel(models.Model):
            ...

            def magic(self, value):
                # Free the ponies

            def thing(self):
                return MethodProxy(self.magic)

        # Usage
        >>> m = MyModel()
        ...
        >>> m.thing['value'] == m.magic('value')

        # template
        {{ m.thing.value }}

        """

        def __init__(self, method):
            self.method = method
        def __getitem__(self, key):
            return self.method(key)

#4


3  

For > 1 argument, use simple tags:

对于> 1参数,使用简单的标签:

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

Template:

模板:

{% for i in channel_status_list %}
  {% related_deltas i 3 4 %}
{% endfor %}

(Note the change of syntax from {{ to {%)

(注意从{到{%)语法的变化

Can take positional parameters (e.g. related_deltas i 3 second_arg=4 debug=true).

可以使用位置参数(例如,related_deltas i 3 second_arg=4 debug=true)。

#5


2  

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

另一个选项是定义属性。见http://adam.gomaa。我们/博客/ 2008 / 8月/ 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à !!!!

就这样! ! ! !

#1


77  

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

#2


30  

If the method doesn't require any arguments, you can use the @property decorator and access it normally in the template.

如果该方法不需要任何参数,您可以使用@property decorator,并在模板中正常地访问它。

class ChannelStatus(models.Model):
    ...
    @property
    def function_you_want_as_property(self):
        mystring = ""
        ...

#3


3  

If you find that there are too many properties running around everywhere or you have a template filter for every other method that you write, another solution was suggested on IRC thanks @FunkyBob. It's a little well, erm, funky but it is nice in certain cases.

如果您发现到处都有太多的属性,或者您为编写的每个其他方法都有一个模板过滤器,那么在IRC上提出了另一种解决方案,感谢@FunkyBob。这有点好,嗯,很时髦,但在某些情况下很不错。

  class MethodProxy(object):
        """For consolidating into 1 method the calling of methods with various single args
        (suitable dictionary keys)

        class MyModel(models.Model):
            ...

            def magic(self, value):
                # Free the ponies

            def thing(self):
                return MethodProxy(self.magic)

        # Usage
        >>> m = MyModel()
        ...
        >>> m.thing['value'] == m.magic('value')

        # template
        {{ m.thing.value }}

        """

        def __init__(self, method):
            self.method = method
        def __getitem__(self, key):
            return self.method(key)

#4


3  

For > 1 argument, use simple tags:

对于> 1参数,使用简单的标签:

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

Template:

模板:

{% for i in channel_status_list %}
  {% related_deltas i 3 4 %}
{% endfor %}

(Note the change of syntax from {{ to {%)

(注意从{到{%)语法的变化

Can take positional parameters (e.g. related_deltas i 3 second_arg=4 debug=true).

可以使用位置参数(例如,related_deltas i 3 second_arg=4 debug=true)。

#5


2  

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

另一个选项是定义属性。见http://adam.gomaa。我们/博客/ 2008 / 8月/ 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à !!!!

就这样! ! ! !