Django custom tags requires 3 arguments, 2 provided

280 Views Asked by At
#custom_tags.py
def modulo(value, number,number2):
    mod = value % number
    if mod == number2:
        return True
    else:
        return False
{% comment %} index.html {% endcomment %}
{% for post in posts|slice:"1:"%}
                      {% if post.id|modulo:4:0 %}
                      <div class="post-entry-1">
                        <a href="{{post.slug}}"><img src="{{post.image.url}}" alt="" class="img-fluid"></a>
                        <div class="post-meta"><span class="date">{{post.category}}</span> <span class="mx-1">&bullet;</span> <span>{{post.created_date}}</span></div>
                        <h2><a href="single-post.html">{{ post.title }}</a></h2>
                      </div>
                      {% endif %}
                      {% endfor %}

TemplateSyntaxError at /blog/ modulo requires 3 arguments, 2 provided

When I mod the value with the variable number, I want to check the result with the variable number2

1

There are 1 best solutions below

2
willeM_ Van Onsem On

You defined a filter, not a tag. A tag can (at most) take two parameters. The object on which the tag is applied and an optional parameter.

You can define a tag with:

from django import template

register = template.Library()


@register.simple_tag
def modulo(value, number, number2=0):
    return value % number == number2

Then you use this with:

{% modulo post.id 4 as md %}
{% if md %}
    …
{% endif %}

That being said, your template seems to implement business logic. This does not belong in the template, but in the view.