简体   繁体   English

将 object 传递给 Django 自定义过滤器

[英]Passing object to Django custom filter

I am using Django 3.2我正在使用 Django 3.2

I am writing a moderation app, and I want to be able to display only approved values in my template.我正在编写一个审核应用程序,我希望能够在我的模板中仅显示批准的值。

I want to be able to use the new filter like this:我希望能够像这样使用新的过滤器:

{{ moderated_object.field_name | approved }}

This is what I have so far:这是我到目前为止所拥有的:

from django import template

register = template.Library()


@register.filter(name='approved')
def moderator_approved_field_value(moderated_object, fieldname):

    return moderated_object.approved_value(fieldname)

As I have written the filter above, I can only use it like this:由于我已经编写了上面的过滤器,所以我只能这样使用它:

{{ moderated_object| approved: fieldname }}

Which is ugly.这是丑陋的。 Is there a way that I can pass the object to the function behind the scenes, so that I can use the cleaner way of using the filter in my template?有没有办法可以在幕后将 object 传递给 function,这样我就可以在模板中使用更简洁的方式使用过滤器?

im my opinion django allow a bad deсigion with template filters.我的意见是 django 允许使用模板过滤器进行错误设计。
You have a template and render function.你有一个模板并渲染 function。 You have a context.你有一个上下文。 You can send in context already the result of moderated_object.approved_value(fieldname).您可以在上下文中发送 modemed_object.approved_value(fieldname) 的结果。

def get_context(...):
    ...
    context[moderated_object] = moderated_object.approved_value(fieldname)
    ...

template模板

{{ moderated_object }}

two }} , not three }}}两个}} ,而不是三个}}}

you can tell me: i create a loop with some additional elements in template.你可以告诉我:我用模板中的一些额外元素创建了一个循环。

answer - additional logic in template is bad, but, if you want - you can create a generator before:答案 - 模板中的附加逻辑不好,但是,如果你愿意 - 你可以在之前创建一个生成器:

def get_context(...):
    ...
    context[moderated_objects] = ((obj, obj.approved_value(fieldname)) for obj in context[moderated_objects])
    ...

template模板

{% for obj, approvement in moderated_objects %}
   {{ approvement }} 
   {{ moderated_object }}
{% endfor %}

all is possible.一切皆有可能。 Try to think completely without template filter.尝试在没有模板过滤器的情况下完全思考。 And you find the best way, i am shure.你会找到最好的方法,我是舒尔。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM