Django template cómo buscar un valor de diccionario con una variable


mydict = {"key1":"value1", "key2":"value2"}

La forma habitual de buscar un valor de diccionario en una plantilla de Django es {{ mydict.key1 }}, {{ mydict.key2 }}. ¿Qué pasa si la clave es una variable de bucle? ie:

{% for item in list %} # where item has an attribute NAME
  {{ mydict.item.NAME }} # I want to look up mydict[item.NAME]
{% endfor %}

mydict.item.NAME falla. ¿Cómo arreglar esto?

Author: MD. Khairul Basar, 2011-11-03

5 answers

Escriba un filtro de plantilla personalizado:

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

(Uso .get de modo que si la clave está ausente, devuelve none. Si lo haces dictionary[key] entonces levantará un KeyError.)

Uso:

{{ mydict|get_item:item.NAME }}
 274
Author: culebrón,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-10-09 14:47:07

Obtenga tanto la clave como el valor del diccionario en el bucle:

{% for key, value in mydict.items %}
    {{ value }}
{% endfor %}

Encuentro esto más fácil de leer y evita la necesidad de codificación especial. Normalmente necesito la clave y el valor dentro del bucle de todos modos.

 35
Author: Paul Whipp,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-07-12 01:13:26

No se puede por defecto. El punto es el separador / disparador para la búsqueda de atributos / búsqueda de claves / sector.

Los puntos tienen un significado especial en la representación de plantillas. Un punto en una variable nombre significa una búsqueda. Específicamente, cuando el sistema de plantillas encuentra un punto en un nombre de variable, intenta las siguientes búsquedas, en este orden:

  • Búsqueda de diccionario. Ejemplo: foo ["bar"]
  • Búsqueda de atributos. Ejemplo: foo.bar
  • Búsqueda de índice de lista. Ejemplo: foo [bar]

Pero puedes hacer un filtro que te permite pasar un argumento:

Https://docs.djangoproject.com/en/dev/howto/custom-template-tags/#writing-custom-template-filters

@register.filter(name='lookup')
def lookup(value, arg):
    return value[arg]

{{ mydict|lookup:item.name }}
 22
Author: Yuji 'Tomita' Tomita,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-04-02 00:06:38

Tuve una situación similar. Sin embargo usé una solución diferente.

En mi modelo creo una propiedad que hace la búsqueda del diccionario. En la plantilla utilizo la propiedad.

En mi modelo: -

@property
def state_(self):
    """ Return the text of the state rather than an integer """
    return self.STATE[self.state]

En mi plantilla: -

The state is: {{ item.state_ }}
 1
Author: sexybear2,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-10-07 00:39:55

Para mí crear un archivo python llamado template_filters.py en mi Aplicación con el contenido a continuación hizo el trabajo

# coding=utf-8
from django.template.base import Library

register = Library()


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

El uso es como lo que dijo culebrón :

{{ mydict|get_item:item.NAME }}
 1
Author: AmiNadimi,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-06-29 19:12:06