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.
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 %}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With