2

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?

Community
  • 1
  • 1
JosephConrad
  • 678
  • 2
  • 9
  • 20

2 Answers2

2

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 %}
Akshar Raaj
  • 14,231
  • 7
  • 51
  • 45
0

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").

jball037
  • 1,780
  • 1
  • 14
  • 18
  • 1
    [for...empty](https://docs.djangoproject.com/en/dev/ref/templates/builtins/#for-empty) looks better, I guess. – awesoon Apr 23 '13 at 15:26