且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Django:在模板中列出模型字段名称和值

更新时间:2023-02-19 07:40:45

不幸的是,您无法在模板引擎中执行类似的查找。

Unfortunately, you can't do lookups like that in the template engine.

您必须在视图中处理该问题。

You'll have to deal with that in the view.

def showdetails(request, template):
    objects = newivr1_model.objects.all()

    for object in objects:
        object.fields = dict((field.name, field.value_to_string(object))
                                            for field in object._meta.fields)

   return render_to_response(template, { 'objects':objects },
                                    context_instance=RequestContext(request))



模板



Template

{% for object in objects %}
    <tr>
    {% for field, value in object.fields.iteritems %}
        <td>{{ field }} : {{ value }}</td>
    {% endfor %}
    </tr>
{% endfor %}