16

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?

3
  • FYI what you are trying to achieve is not called concatenation Commented Aug 22, 2015 at 16:30
  • Thanks. how is called? Commented Aug 22, 2015 at 16:32
  • Updated your question and check my answer. Thanks! Commented Aug 22, 2015 at 16:43

2 Answers 2

17

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.

Sign up to request clarification or add additional context in comments.

Comments

3

Fixed answer for non string attributes

The selected answer don't cover cases where you need to access non string attributes.

If you are trying to access an attribute that isn't a string, then you must use this code:

from django import template

register = template.Library()

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

For this, create a folder named templatetags on your app's folder, then create a python file with whatever name you want and paste the code above inside.

Inside your template load your brand new filter using the {% load YOUR_FILE_NAME %}, be sure to change YOUR_FILE_NAME to your actual file name.

Now, on your template you can access the object attribute by using the code bellow:

{{ PUT_THE_NAME_OF_YOUR_OBJECT_HERE|get_obj_attr:PUT_THE_ATTRIBUTE_YOU_WANT_TO_ACCESS_HERE }}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.