0

视图.py

@register.filter(name="avl")
def avl_facilities(obj):
    return obj.avl_facilities()

@register.filter
def na_facilities(obj):
    return obj.na_facilities()

模型.py

class Model(models.Model):
#some code .....
    def avl_facilities(self):
        item = ['bar','bank','music','wifi','offers','credit']
        avl = []
        for i in item:
            if getattr(self,i) == True:
                avl.append(i)
        return avl
    def na_facilities(self):
        item = ['bar','bank','music','wifi','offers','credit']
        na = []
        for i in item:
            if getattr(self,i) == False:
                na.append(i)
        return na

html

<div class="facility pad10">
    {% for item in data.rest|avl %}
/* data.rest is appropriate instance of model defined above*/
    <span class="label label-danger mrg2 pad5 pull-left">
    {{item|title}}
    </span>
    {% endfor %}
</div>

错误

Invalid filter: 'avl_facilities'

怀疑

我无法理解,如果模型中的 avl_facilities 返回正确的可迭代列表,但它不能作为模板过滤器工作,在此先感谢

4

1 回答 1

3

您不能在 views.py 中定义过滤器。您必须将它们放在 templatetags 目录中的新文件中。

您应该知道,这两个过滤器都是完全没有必要的。很可能从模板调用模型方法,只要它们不带参数:

{% for item in data.rest.avl_facilities %}
于 2012-08-23T06:28:21.343 回答