I am using 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?
im my opinion django allow a bad deсigion with template filters.
You have a template and render function. You have a context. You can send in context already the result of moderated_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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.