Django模板:如何访问一个等于变量值的表单域? [英] Django templates: How to access a form field equal to a variable value?

查看:114
本文介绍了Django模板:如何访问一个等于变量值的表单域?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

想象一下下面的用例:我有一个报告模板的字典。每个报告模板都有一个ID和一个名称。它看起来或多或少是这样的:

Imagine a following use case: I have a dictionary of report templates. Each report template has an ID and a name. It looks more or less like this:

reports = [ { 'ID' : 'A1',
              'NAME' : 'special report 1 for department A',
              ... (other fields irrelevant to the question's matter)
            },
            { 'ID' : 'X9',
              'NAME' : 'special report 9 for department X',
              ... (other fields irrelevant to the question's matter)
            },
          ]

访问和可见性的报告将被存储在数据库中。

我创建了一个字段名称等于报告ID。一切顺利,直到我必须在模板中显示表单。我不知道如何访问正确的表单的字段。此语法无效:

Access to and visibility of the reports are to be stored in a database.
I created a form with field names equal to reports' IDs. And everything goes fine until the moment I have to show the form in the template. I don't know how to access the proper form's field. This syntax doesn't work:

{% for report in reports %}
<tr>
    <td>{{ report.ID }}</td>
    <td>{{ report.NAME }}</td>

    <td>{{ form.report.ID }}</td>

</tr>
{% endfor %} 

另外:

{% for report in reports %}
<tr>
    <td>{{ report.ID }}</td>
    <td>{{ report.NAME }}</td>
    {% with report.ID as key %}     
    <td>{{ form.key }}</td>
    {% endwith %}
</tr>
{% endfor %} 

无效。

语法应该如何?在下面的代码中应该放置什么而不是问号?

How should the syntax look like? What should be placed instead of the question marks in the code below?

{% for report in reports %}
<tr>
    <td>{{ report.ID }}</td>
    <td>{{ report.NAME }}</td>

    <td>{{ form.??? }}</td>

</tr>
{% endfor %} 

我越过了这个解决方案: Django模板:表单字段名称作为变量,我想我将不得不使用它没有其他办法可以解决我的问题。

I crossed upon this solution: Django Templates: Form field name as variable? and I guess I'll have to use it if there won't be any other way to solve my problem.

推荐答案

这是不鼓励的,因为模板应该尽可能没有逻辑。但是,实际上,这一直都出现了。您可以制作一个模板过滤器:

It's discouraged because the templates are supposed to be as without logic as possible. But, in practice, this comes up all the time. You can make a template filter that does this:

@register.filter(name='get')
def get(o, index):
    try:
        return o[index]
    except:
        return settings.TEMPLATE_STRING_IF_INVALID

然后,在模板中,正确加载模板库后:

Then, in the template, after you load the templatetags library appropriately:

{% for report in reports %}
<tr>
    ...
    <td>{{ form|get:report.ID }}</td>
</tr>
{% endfor %} 

这篇关于Django模板:如何访问一个等于变量值的表单域?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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