我在Django上创建模板以显示带有2个按钮的项目列表。
我的表格类别:
class AppsForm(forms.Form):
def __init__(self, *args, **kwargs):
policiesList = kwargs.pop('policiesList', None)
applicationList = kwargs.pop('applicationList', None)
EC2nodesList = kwargs.pop('amazonNodesList', None)
super(AppsForm, self).__init__(*args, **kwargs)
self.fields['appsPolicyId'] = forms.ChoiceField(label='Application Policy', choices=policiesList)
self.fields['appsId'] = forms.ChoiceField(label='Application', choices=applicationList)
self.fields['ec2Nodes'] = forms.ChoiceField(label='Amazon EC2 Nodes', choices=EC2nodesList)
现在,我用以下表格填写:
<form method="post" action="" class="form-inline" role="form">
<div class="form-group">
{% for field in form %}
{ field.label }}: {{ field}}
{% endfor %}
</div>
{% csrf_token %}
<input type="submit" class="btn btn-default btn-success" name="deployButton" value="Deploy"/>
<input type="submit" class="btn btn-default btn-danger" name="undeployButton" value="Undeploy"/>
结果是:
Application Policy - Choicefield ; Application - Choicefield ; Amazon EC2 Nodes - Choicefield [Button Deploy] [Button Undeploy]
而我正在寻找的是一种呈现表单并显示如下列表的方法:
Application Policy - Choicefield ; Application - Choicefield [Button Deploy] [Button Undeploy]
Amazon EC2 Nodes - Choicefield [Button Deploy] [Button Undeploy]
<more items if I add them in forms.py...>
我如何才能获得正确的渲染方式?
谢谢和问候。
答案 0 :(得分:1)
您只需更改代码即可:
{% for field in form %}
{ field.label }}: {{ field}}
<input type="submit" class="btn btn-default btn-success" name="deployButton" value="Deploy"/>
<input type="submit" class="btn btn-default btn-danger" name="undeployButton" value="Undeploy"/>
<br />
{% endfor %}
因此,这将使用各自的按钮为每个field.label和field变量创建一个新行。但要注意的一件事是,如果您尝试将ID分配给按钮,则它们必须不同,否则您将收到错误。此外,提交可能有点奇怪的代码,但这取决于您的应用程序的其余部分。无论哪种方式,这将为您提供所需的格式。