show a field knowing its name in a django template

1

if I have a "person" model with a "name" field to show the field in a template I use

{{person.name}}

But as it is done when I have the name of the field in a variable. For example:

nombrecampo='nombre'    
{{persona[nombrecampo]}} 

or simpler

{{persona['nombre']}}

obviously the above does not work.

I have found a solution by creating a custom template tag ie

#fichero: mi_template_tag.py    
@register.filter
def get_attr (obj,atributo):
    return getattr(obj,atributo)

then in the template I can do the following

{% import mi_template_tag %}
<p> {{persona|get_attr:'nombre'}} </p>

Should there be a simpler way to do this right?

    
asked by user1640529 30.07.2018 в 15:38
source

0 answers