Home > Net >  Can you access variable attributes in the django template language with other variables?
Can you access variable attributes in the django template language with other variables?

Time:12-01

Let's say I have two variables - User and Fruitlist. User is a model instance, while fruitlist is a list.

{% for user in users %}
            <tr>
                <td>{{ user.title }} </td>
                <td>{{ user.text }} </td>
                {% for fruit in fruitlist %}
                        <td>{{ user.fruit }} </td>
                {% endfor %}
        {% endfor %}

I'm trying to create a table with the code above where a column is created for each fruit in fruitlist, and that column is filled with the value of an attribute user.fruit (the user model has a field for every fruit which contains a value).

Why doesn't the above code work?

CodePudding user response:

Your code doesn't work, because the attribute fruit is interpreted as a string.

You can write a custom filter to retrieve attributes as variables in your templates.

# your_app_name/templatetags/your_app_name_tags.py
from django import template

register = template.Library()

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

Then in your template

{% load your_app_name_tags %}

{% for user in users %}
            <tr>
                <td>{{ user.title }} </td>
                <td>{{ user.text }} </td>
                {% for fruit in fruitlist %}
                        <td>{{ user|get_attr:fruit }} </td>
                {% endfor %}
{% endfor %}

CodePudding user response:

Replace:

<td>{{ user.fruit }} </td>

With:

<td>{{ user[fruit] }} </td>

Luckily you can access an attribute like it was a dictionary key here.

Although, from what you have described, this might not be the correct solution.

If the list of fruits is like:

fruitlist = ['apple', 'orange', 'banana'] 

Then it should be an applicable solution

  • Related