在模板中迭代模型实例字段名称和值 [英] Iterate over model instance field names and values in template

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

问题描述

我正在尝试创建一个基本模板来显示所选实例的字段值及其名称。将其视为表格格式中该实例的值的标准输出,第一列中的字段名称(详细说明如何在字段中指定),第二列中该字段的值为。

I'm trying to create a basic template to display the selected instance's field values, along with their names. Think of it as just a standard output of the values of that instance in table format, with the field name (verbose_name specifically if specified on the field) in the first column and the value of that field in the second column.

例如,假设我们有以下模型定义:

For example, let's say we have the following model definition:

class Client(Model):
    name = CharField(max_length=150)
    email = EmailField(max_length=100, verbose_name="E-mail")

我希望它在模板中输出,如下所示(假设具有给定值的实例):

I would want it to be output in the template like so (assume an instance with the given values):

Field Name      Field Value
----------      -----------
Name            Wayne Koorts
E-mail          waynes@email.com

我想要实现的是能够通过将模型的实例转换为模板,并能够在模板中动态迭代,如下所示:

What I'm trying to achieve is being able to pass an instance of the model to a template and be able to iterate over it dynamically in the template, something like this:

<table>
    {% for field in fields %}
        <tr>
            <td>{{ field.name }}</td>
            <td>{{ field.value }}</td>
        </tr>
    {% endfor %}
</table>

有没有一个整洁的Django批准的方式来做到这一点?这似乎是一个很常见的任务,我需要经常为这个特定的项目做。

Is there a neat, "Django-approved" way to do this? It seems like a very common task, and I will need to do it often for this particular project.

推荐答案

我来了使用以下方法,这对我有用,因为在每种情况下,模型将有一个ModelForm与之相关联。

I've come up with the following method, which works for me because in every case the model will have a ModelForm associated with it.

def GetModelData(form, fields):
    """
    Extract data from the bound form model instance and return a
    dictionary that is easily usable in templates with the actual
    field verbose name as the label, e.g.

    model_data{"Address line 1": "32 Memory lane",
               "Address line 2": "Brainville",
               "Phone": "0212378492"}

    This way, the template has an ordered list that can be easily
    presented in tabular form.
    """
    model_data = {}
    for field in fields:
        model_data[form[field].label] = eval("form.data.%s" % form[field].name)
    return model_data

@login_required
def clients_view(request, client_id):
    client = Client.objects.get(id=client_id)
    form = AddClientForm(client)

    fields = ("address1", "address2", "address3", "address4",
              "phone", "fax", "mobile", "email")
    model_data = GetModelData(form, fields)

    template_vars = RequestContext(request,
        {
            "client": client,
            "model_data": model_data
        }
    )
    return render_to_response("clients-view.html", template_vars)

模板我正在使用这个特定的视图:

Here is an extract from the template I am using for this particular view:

<table class="client-view">
    <tbody>
    {% for field, value in model_data.items %}
        <tr>
            <td class="field-name">{{ field }}</td><td>{{ value }}</td>
        </tr>
    {% endfor %}
    </tbody>
</table>

这个方法的好处是我可以按模板的顺序选择在其中我想显示字段标签,使用传入到GetModelData的元组并指定字段名称。这也允许我排除某些字段(例如用户外键),因为只有通过元组传递的字段名称才被构建到最终的字典中。

The nice thing about this method is that I can choose on a template-by-template basis the order in which I would like to display the field labels, using the tuple passed in to GetModelData and specifying the field names. This also allows me to exclude certain fields (e.g. a User foreign key) as only the field names passed in via the tuple are built into the final dictionary.

我是不要接受这个答案,因为我确定有人可以想出更多的Djangonic: - )

I'm not going to accept this as the answer because I'm sure someone can come up with something more "Djangonic" :-)

更新:我选择这个作为最后的答案,因为它是最简单的,给出了我需要的。感谢所有提供答案的人。

Update: I'm choosing this as the final answer because it is the simplest out of those given that does what I need. Thanks to everyone who contributed answers.

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

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