我想打印我的个人资料模板中的所有用户值。 手动打印它的工作原理: `
<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>`
但是这种方法不起作用: `
<table class="table table-striped table-bordered">
{% for field in user.fields %}
<tr>
<td>{{ field.name }}</td>
<td>{{ field.value }}</td>
</tr>
{% endfor %}
</table>
我正在尝试使用这种方法 Iterate over model instance field names and values in template
有什么提示吗?
最佳答案
模型实例上没有可用的名为 fields 的属性。
如果你真的想要这样的东西:
views.py:
d = {}
for each in u._meta.fields:
d[each.name] = getattr(u, each.name)
模板:
{% for k,v in d.items %}
{{k}}
{{v}}
{% endfor %}
关于django - 在 django 模板中迭代用户,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16172937/