Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django custom filter error. Returns "invalid filter"

Tags:

python

django

I've been trying to create this custom filter in Django, and I can't for the life of me make it work.

in my templatetags folder I have the files __init__.py and alcextra.py in my template I first load the static files and then the templatetags. I've tried reseting the server and deleting and creating the files again.

{% load staticfiles %} {% load alcextra %} Which is then extended to my main html file. I have tried putting it in the main html file.

in alcextra.py I have written

from django import template
register = template.Library()

@register.filter
def multiply(value, arg):
    return value * arg

I have tried loads of different @register versions like

@register.filter("multiply", multiply) @register.filter(name="multiply") @register.filter() @register.simple_tag(takes_context=True

And all return the same error, invalid filter: 'multiply'. At this point I don't know what to do or what to try.

Overview of the directory

Edit: the template in question.

<!DOCTYPE html> {% load staticfiles %} {% load alcextra %}
<html>

<head>
  <script src="../../static/javascript/jquery-3.2.1.js"></script>
  <link rel="stylesheet" href="{% static 'css/alcosearch.css' %}" />
  <title>Alcosearch</title>
  <meta charset="utf-8" />
</head>

<body>
  <div class="pageheader">
    <h1>Alcosearch</h1>
    <h3>Vinmonopol søk</h2>
  </div>
  <div>
    {% block content %} {% endblock %}
  </div>
  </body>

</html>

What is annoying is that I tried this in another project and it worked. So I'm not completely sure what I've done or not done.

Edit 2:

The answer is what @Alasdair said. I thought I could load the filter in the template and then use it somewhere else, which was not the case.

like image 381
Paalar Avatar asked Oct 03 '17 22:10

Paalar


1 Answers

It is a documented feature of the Django template language that when you load a custom tag or filter, it is not automatically available in the child template.

You are not using the filter in the base template, so you don't need to load the alcextra library there.

Then add the load statement to any child templates that use the filter, for example:

{% extends "base.html" %}
{% load alcextra %}
{% block content %}
{{ my_value|multiply:5 }}
{% endblock content %}
like image 169
Alasdair Avatar answered Sep 30 '22 18:09

Alasdair