Search code examples
djangodjango-templatesdjango-settingsdjango-appsdjango-custom-tags

Django custom tags validation


I'm getting this error -> Invalid filter: 'cutter' while this is my custom tags.py:

from django import template
from random import randint

register = template.Library()


def cutter(list, args):
    return list[args]

register.filter('cutter', cutter)

a short part of index.html:

{% extends 'main.html' %}
{% load custom_tags %}
{% load humanize %}
{% load static %}
{% block title %}main{% endblock title %}
{% block home %}active{% endblock home %}
{% block body %}

<span>{{regions_count|cutter:forloop.counter0}}</span>

{% endblock body %}

and my directory is this:

my_app/
├── ...
├── templatetags/
│   ├── __init__.py
│   └── _pycache_(folder)
|   └── custom_tags.py
└── views.py

Solution

  • I tried it with following:

    custom_tags.py (list is a bad name for a variable - because it shadows built in list function)

    from django import template
    
    register = template.Library()
    
    def cutter(entry_list, args):
        return entry_list[args]
    
    register.filter('cutter', cutter)
    

    index.html:

    {% extends 'admin/base.html' %}
    
    {% load custom_tags %}
    {% block title %}main{% endblock title %}
    
    {% block content %}
        <span>{{ regions | cutter:0 }}</span>
    {% endblock %}
    

    views.py:

    from django.shortcuts import render
    from django.http import HttpResponse
    from .models import Region
    
    def index(request):
        context = {
            'regions': Region.objects.all()
        }
        return HttpResponse(render(request, 'index.html', context))
    

    and this directory structure:

    my_project
    ├── my_app/
    |  ├── ...
    |  ├── templates
    |  |   └── index.html
    |  ├── templatetags/
    |  |   └── custom_tags.py
    |  └── views.py
    

    Everything works fine and I get the first Region object printed.