About django custom filter arguments

Recently, I just started doing Python for data analysis etc., and when I was using Django to do WebView with Python anyway, I tried to create a custom filter and refer to it in order to refer to the dictionary object from the template side. When I did, there was a part I was addicted to, so I will write it down here.

Custom filter

One of the functions you can call in Django templates http://django-docs-ja.readthedocs.org/en/latest/howto/custom-template-tags.html

Custom filter that references dictionary objects templatetags/helper.py

from django import template
register = template.Library()

def get_dict_val(var,args):
    dict_val = var
    keys = [arg.strip() for arg in args.split(',')]
    for key in keys:
        dict_val = dict_val[key]
    return dict_val
register.filter('dict_val',get_dict_val)

--Template side

{{ dict_obj|get_dict_val:'key1,key2' }}

You can refer to the dictionary object in this way. You can refer to multi-level objects by separating them with commas.

{"1":{"0001":"Sales department"}}

However, with this method, the argument from the template side can only be processed as a character string, so variables cannot be passed to the custom filter. (Processing objects in for loop, etc.)

--Template side

#error
{% for row in data %}
  <p>{{ dict_obj|get_dict_val:row.no,row.busho_code }}</p>
{% endfor %}

Conclusion

Once, I created a string with two variables separated by commas, and then passed it as an argument.

--Added a comma-comma function to your custom filter templatetags/helper.py

def join_comma(var,args):
    return "%s,%s" % (var,args)
register.filter('join_comma',join_comma)

--Template side Variables can be created temporarily by using the with template tag

{% for row in data %}
  {% with row.no|join_comma:row.busho_code as shain_id %}
  <p>{{ dict_obj|get_dict_val:shain_id }}</p>
  {% endwith %}
{% endfor %}

There seems to be some debate about custom filter arguments. https://code.djangoproject.com/ticket/1199

I think that it is necessary to design it so that it can be done on the view side as much as possible, but there may be situations where the template side must directly access the dictionary object due to the specifications, so I left the method above.

Recommended Posts

About django custom filter arguments
Django filter summary
About function arguments (python)
About scipy Gaussian filter
Python: About function arguments
About handling Django static files
Dive into the Django Custom command [1]
Make a filter with a django template
[Django] About one-to-many relationships (related_name, _set.all ())
A story about custom users having a sweet and painful look at Django