Django自定义过滤器错误。返回“无效过滤器” [英] Django custom filter error. Returns "invalid filter"

查看:256
本文介绍了Django自定义过滤器错误。返回“无效过滤器”的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在尝试在Django中创建此自定义过滤器,但我终生无法使其正常工作。

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

在我的templatetags文件夹中我的模板中有文件 __ init __。py alcextra.py ,我先加载静态文件,然后加载templatetags。我尝试重置服务器,然后再次删除并创建文件。

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%}
然后将其扩展到我的主要html文件。我已经尝试将其放在主html文件中。

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

在alcextra.py中,我已经写过

in alcextra.py I have written

from django import template
register = template.Library()

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

我曾尝试加载不同的@register版本,例如

I have tried loads of different @register versions like

@ register.filter(乘法,相乘)
@ register.filter(name = multiply)
@ register.filter()
@ register.simple_tag(takes_context = True

全部返回相同的错误,无效的过滤器: multiply。我不知道该怎么办或尝试什么。

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

目录概述

编辑:相关模板。

<!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.

编辑2:

答案是@Alasdair说的。我以为可以将过滤器加载到模板中,然后在其他地方使用它,情况并非如此。

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.

推荐答案

一个记录的功能 Django模板语言,当您加载自定义标签或过滤器时,子模板中不会自动提供该标签。

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.

您没有在基本模板中使用过滤器,因此您无需在其中加载 alcextra 库。

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

然后将load语句添加到使用过滤器的所有子模板中,例如:

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 %}

这篇关于Django自定义过滤器错误。返回“无效过滤器”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆