In a Django template, how to specify a dictionary key which is itself an attribute?

前端 未结 2 2003
感动是毒
感动是毒 2021-01-25 15:07

I\'m working on a Django project with a ListView that has both a search form, known in the view\'s context as search_form, and a filter form, fil

2条回答
  •  说谎
    说谎 (楼主)
    2021-01-25 15:40

    I finally solved this by writing a custom get filter as described in Django template how to look up a dictionary value with a variable:

    from django import template
    
    register = template.Library()
    
    
    @register.filter
    def get(dictionary, key):
        return dictionary.get(key)
    

    I updated _search.html as follows:

    {% load get %}
    
    
    

    Now, if I try to search a filtered result, it works as expected:

    Note that this also works fine for the filters that are not applied - these have the value None instead of an empty string - without any need to filter them out in the form.

提交回复
热议问题