JosephConrad
JosephConrad

Reputation: 688

Iterating over user in django template

I would like to print all user values in my profile template. Printing it manually it works: `

<table class="table table-striped table-bordered"> 
    <tr><th>{{ user.username }}</th></tr>
    <tr><th>{{ user.first_name }}</th></tr>
    <tr><th>{{ user.last_name }}</th></tr>
    <tr><th>{{ user.email }}</th></tr>
</table>`

but such approach does not work: `

<table class="table table-striped table-bordered">
    {% for field in user.fields %}
        <tr>
            <td>{{ field.name }}</td>
            <td>{{ field.value }}</td>
        </tr>
    {% endfor %}
</table>

I was tryintg to use this approach Iterate over model instance field names and values in template

Any hints?

Upvotes: 2

Views: 876

Answers (2)

Akshar Raaj
Akshar Raaj

Reputation: 15211

There is no attribute called fields available on model instances.

If you really want something like this:

views.py:

d = {}

for each in u._meta.fields:
    d[each.name] = getattr(u, each.name)

template:

{% for k,v in d.items %}
    {{k}}
    {{v}}
{% endfor %}

Upvotes: 2

jball037
jball037

Reputation: 1800

You have to make sure you're sending in the "user" object itself through your views.py file (not user.username, or user.first_name, etc.). That way you can write in your template:

<table class="table table-striped table-bordered">
        {% for field in user %}
            <tr>
                <td>{{ field.name }}</td>
                <td>{{ field.value }}</td>
            </tr>
        {% empty %}
            <tr>
                <td>No "user" field</td>
            </tr>
        {% endfor %} 
</table>

Notice the change in the second line ("for field in user").

Upvotes: 0

Related Questions