Django:在模板中列出模型字段名称和值 [英] Django : Listing model field names and values in template

查看:1472
本文介绍了Django:在模板中列出模型字段名称和值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

Django - 在模板中迭代模型实例字段名称和值

我试图在模板中列出通用Django模型的字段和对应的值。然而,我找不到一个相当常见的问题的内置解决方案。我非常接近解决方案,但找不到出路。

I'm trying to list fields and corresponding values of generic Django models in the templates. However I can't find an inbuilt solution for a fairly common problem. I'm pretty close to the solution but can't find a way out.

view.py代码:

view.py Code:

def showdetails(request, template):
    objects = newivr1_model.objects.all()
    fields = newivr1_model._meta.get_all_field_names()
    return render_to_response(template, {'fields': fields,'objects':objects},
        context_instance=RequestContext(request))

模板代码:

    <table>                                                                                                                                       
    {% for object in objects %}                                                 
        <tr>                                                                    
            {% for field in fields %}                                           
                <td>                                                            
            <!--    {{ object.field }} /*This line doesn't work*/ -->                                           
                </td>                                                           
            {% endfor %}                                                        
        </tr>                                                                   
    {% endfor %}                                                                
    </table>

我在评论的模板行中应该怎么做,以便获得Object.field的值?

What should I be doing at the commented template line so that i get the value of Object.field?

任何更好的DRY方法也是最受欢迎的。

Any better DRY methods are most welcome as well.

推荐答案

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

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

这篇关于Django:在模板中列出模型字段名称和值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆