django自定义标签将某个字段传递到过滤器中
我正在使用 django-simple-history 来记录对模型的更改,我为模型编写了一堆自定义方法,以从历史记录中提取最新的更改日期,每个我感兴趣的字段一个,但它很多重复而且一点也不干。
在我看来,我应该能够使用自定义标签并传递我想要的字段来简化它,但我似乎无法让它工作。
customtags.py:
from django import template
register = template.Library()
@register.simple_tag
def get_latest_record(issue, field):
record = issue.history.filter(field = 1).most_recent
return record
在我的模板中:
{% get_latest_record issue 'name_of_field' %}
I am using django-simple-history to record changes to a model, I've written a bunch of custom methods for the model to extract the latest change date from the history, one for each field I'm interested in but it's a lot of duplication and really not at all DRY.
It seems to me that I should be able to simplify this using a custom tag and passing the field that I want but I can't seem to get it to work.
customtags.py:
from django import template
register = template.Library()
@register.simple_tag
def get_latest_record(issue, field):
record = issue.history.filter(field = 1).most_recent
return record
in my template:
{% get_latest_record issue 'name_of_field' %}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
确保您的
customtags.py
文件位于templatetags
目录中(还需要__init__.py
),然后重新启动服务器然后在模板
中{%加载自定义标签%}
Make shure your
customtags.py
file is intemplatetags
directory (__init__.py
is also required) and then restart serverThen in template
{% load customtags %}