django自定义标签将某个字段传递到过滤器中

发布于 2025-01-12 12:12:50 字数 480 浏览 2 评论 0原文

我正在使用 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

心意如水 2025-01-19 12:12:50

确保您的 customtags.py 文件位于 templatetags 目录中(还需要 __init__.py),然后重新启动服务器

polls/
__init__.py
models.py
templatetags/
    __init__.py
    poll_extras.py
views.py

然后在模板 中{%加载自定义标签%}

Make shure your customtags.py file is in templatetags directory (__init__.py is also required) and then restart server

polls/
__init__.py
models.py
templatetags/
    __init__.py
    poll_extras.py
views.py

Then in template {% load customtags %}

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文