Django templates: How to access a form field equal to a variable value?

余生长醉 提交于 2019-12-13 14:31:37

问题


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)
            },
          ]

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

Also:

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

doesn't work.

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

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.


回答1:


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



回答2:


Try this:

{{ form.fields.key }}


来源:https://stackoverflow.com/questions/11526420/django-templates-how-to-access-a-form-field-equal-to-a-variable-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!