Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access an attribute of an object using a variable in django template?

How can I access an attribute of an object using a variable? I have something like this:

{% for inscrito in inscritos %}
   {% for field in list_fields_inscrito %}
      {{inscrito.field}} //here is the problem
   {% endfor %}
{% endfor %}

For example Inscrito have: inscrito.id, inscrito.Name and inscrito.Adress and I only want to print inscrito.id and inscrito.Name because id and Name are in the list_fields_inscrito.

Does anybody know how do this?

like image 428
Perico Avatar asked Aug 22 '15 15:08

Perico


People also ask

How do you pass variables from Django view to a template?

And this is rather simple, because Django has built-in template modules that makes a transfer easy. Basically you just take the variable from views.py and enclose it within curly braces {{ }} in the template file.

What does {{ this }} mean in Django?

{{ foo }} - this is a placeholder in the template, for the variable foo that is passed to the template from a view. {% %} - when text is surrounded by these delimiters, it means that there is some special function or code running, and the result of that will be placed here.

What does {% include %} do in Django?

The include tag allows you include a template inside the current template. This is useful when you have a block of content that are the same for many pages.


1 Answers

You can write a template filter for that:

myapp/templatetags/myapp_tags.py

from django import template

register = template.Library()

@register.filter
def get_obj_attr(obj, attr):
    return getattr(obj, attr)

Then in template you can use it like this:

{% load myapp_tags %}

{% for inscrito in inscritos %}
   {% for field in list_fields_inscrito %}
      {{ inscrito|get_obj_attr:field }}
   {% endfor %}
{% endfor %}

You can read more about writing custom template tags.

like image 117
Aamir Rind Avatar answered Sep 27 '22 17:09

Aamir Rind