如何在模板Django中渲染表单集并创建垂直表? [英] How to render formset in template django and create vertical table?
问题描述
如何使用formset和extra = 3创建此表?
How to create this table used formset and extra=3?
表:
| my name first column | second column | third column | fourth column |
| formset1.field1.label | formset1.field1 | formset2.field1 | formset3.field1 |
| formset1.field2.label | formset1.field2 | formset2.field2 | formset3.field2 |
| formset1.field3.label | formset1.field3 | formset2.field3 | formset3.field3 |
| formset1.field4.label | formset1.field4 | formset2.field4 | formset3.field4 |
在视图中,我创建标准表单集:
In view I create standard formset:
def my_view(request, id_object):
getobject = get_object_or_404(Model, id=id_object)
FormSetInit = inlineformset_factory(Model, Model2, form=FormModel2, extra=3)
FormSet = FormSetInit(instance=getobject, prefix='model2')
response = {}
response['Formset'] = FormSet
return render_to_response('my_template.html', response)
在模板 my_template.html中,我尝试使用以下方法:
In template 'my_template.html' i try used this:
<table>
{% for form in Formset %}
{% if forloop.counter == 1 %}
{% for field in form %}
{% if forloop.counter < 8 %}
<tr>
<td class="first">{{ field.label }}</td>
<td>{{ field }}</td>
<td>{{ field }}</td>
<td class="last">{{ field }}</td>
{% if forloop.counter != 7 %}
</tr>
{% endif %}
{% else %}
{{ field }}
{% if forloop.last %} </tr> {% endif %}
{% endif %}
{% endfor %}
{% endif %}
{% endfor %}
</table>
但这不是一个好主意..:/
But this not a good idea.. :/
推荐答案
我也遇到了麻烦,但是设法在 https://docs.djangoproject.com/en/dev/topics/forms/?from=olddocs #displaying-a-form-using-a-template
I was having trouble with this too but managed to get it to work with some help from https://docs.djangoproject.com/en/dev/topics/forms/?from=olddocs#displaying-a-form-using-a-template
无论如何,这是您可以尝试使用的模板,它基本上会遍历每个形式:
Anyways, this is what you can try for the template, it basically iterates through each of the forms:
<table>
<thead>
{% for form in Formset.forms %}
{% if forloop.first %}
{% for field in form %}
<th>{{ field.label_tag }}</th>
{% endfor %}
{% endif %}
</thead>
<tbody>
<tr>
{% for field in form %}
<td>{{ field }}</td>
{% endfor %}
</tr>
{% endfor %}
</tbody>
</table>
希望有帮助!不知道这是否是最好的方法,但它确实有效!
Hope that helps! Not sure if it's the best way to do it, but it worked!
这篇关于如何在模板Django中渲染表单集并创建垂直表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!