2012-08-23 132 views
0

views.py

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

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

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

errro

Invalid filter: 'avl_facilities' 

d oubt

我不能夠理解的是,如果模型裏面的avl_facilities提前返回正確的迭代列表,但它不工作爲模板過濾器,感謝Django的創建模板過濾器

回答

3

不能定義在views.py過濾器。您必須將它們放在templatetags目錄中的新文件中。

你應該知道這兩個過濾器是完全不必要的。從模板中調用模型方法是非常有可能的,只要它們沒有參數:

{% for item in data.rest.avl_facilities %} 
+0

謝謝但是過濾器有什麼特別的,可以請幫忙 – Abhimanyu