django creating template filters
-
27-06-2021 - |
Question
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'
doubt
i am not able to understand that if the avl_facilities inside the model is returning proper iterable list , but its not working as a template filter , thanks in advance
Solution
You can't define filters in views.py. You have to put them in a new file inside a templatetags directory.
You should know though that both of these filters are totally unnecessary. It's quite possible to call model methods from the template, as long as they don't take arguments:
{% for item in data.rest.avl_facilities %}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow