Home > OS >  Django Custom Filter Tags and access query
Django Custom Filter Tags and access query

Time:10-04

Hi need some help on Django custom filter tag, much appreciated!

I have registered a filter tag to access dictionary in HTML files like below:

DIRECTORY - blog>templatetags>post_extras.py

@register.filter
def get_item(dictionary, key):
    return dictionary.get(key)

A dictionary named dict_post, the key is the post id, and the values is the query set. Let say to get dictionary key of 1:

DIRECTORY - blog>templates>blog>home.html

{{ dict_post|get_item:1 }}

It returns 'title' and 'date_posted' in a queryset

Post('dsdsdsdqqq111', '2021-10-03 10:24:40.623754 00:00')

It worked well for the filter tag, but when I want to access some query after the filter tags , it return errors. How to only get the title? I have tried the code like below, but return errors

DIRECTORY - blog>templates>blog>home.html

{{ dict_post|get_item:1.title }}

Error:

VariableDoesNotExist at /

Looking for help, thanks!

CodePudding user response:

You can use the {% with … %} … {% endwith %} template tag [Django-doc]:

{% with somevar=dict_post|get_item:1 %}
    {{ somevar.title }}
{% endwith %}

since we here know that the key is 1 (likely that will later change), we can work with:

{# if the key is known to be 1 #}
{{ dict_post.1.title }}

That being said, normally it is better to "prepare" the data in the view in such way that you do not need to perform dictionary lookups with a variable key. The Django template language is deliberately restricted to prevent people from writing business logic in the template.

  • Related