I'm trying to create a custom template filter but, getting Invalid filter
error.
TemplateSyntaxError at /attainment/reportcard/
Invalid filter: 'get_item'
Request Method: POST
Request URL: http://127.0.0.1:8000/attainment/reportcard/
Django Version: 1.11.5
Exception Type: TemplateSyntaxError
Exception Value:
Invalid filter: 'get_item'
Exception Location: /media/itsd/ITSD/ROFI/Projects/Rise/venv/lib/python3.5/site-packages/django/template/base.py in find_filter, line 606
Python Executable: /media/itsd/ITSD/ROFI/Projects/Rise/venv/bin/python
Python Version: 3.5.2
I've created a filter in template_filters.py
and registered.
template_filters.py
from django.template.defaulttags import register
# Custom template filter to get data from a dictionary using key in template
@register.filter
def get_item(dictionary, key):
return dictionary.get(key)
And I've used the filter in the template as follows.
<tbody>
{% for subject in subjects %}
<tr>
<td>{{ subject|get_item:"subject" }}</td>
<td>{{ subject|get_item:"efffort" }}</td>
<td>{{ subject|get_item:"homework" }}</td>
<td>{{ subject|get_item:"marks" }}</td>
<td>{{ subject|get_item:"grade" }}</td>
</tr>
{% endfor %}
</tbody>
What am I missing ??
N.B: I've followed this answer.
You have to load the tag library before you use it in the template:
{% load template_filters %}
Or you can load the specific filter:
{% load get_item from template_filters %}
See the docs on custom template tags and the {% load %}
tag for more info.