Search code examples
djangodjango-templatesdjango-template-filters

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


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?

EDIT:

Solution for original question bellow - following is regarding forms

For forms:

{% for fruit in fruits %}
                {% if user|get_attr:fruit != True %}
                    {{ form|get_attr:fruit }}
                {% else %}
                    <p>&#10003; {{ fruit }}</p>
                {% endif %}
            {% endfor %}

Solution

  • 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 %}