Abhimanyu
Abhimanyu

Reputation: 589

django creating template filters

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

Upvotes: 0

Views: 92

Answers (1)

Daniel Roseman
Daniel Roseman

Reputation: 599610

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

Upvotes: 3

Related Questions