我使用formset生成额外字段,但是我不知道如何更改formset生成的额外字段的标签。在
我的代码:
class GetMachine(forms.Form):
Number_of_Lines = forms.IntegerField(max_value=4)
class GetLine(forms.Form):
beamline_name = forms.CharField(max_length=15, label='Name of Beamline-%i')
def install(request):
MachineFormSet = formset_factory(GetMachine, extra=1)
formset = MachineFormSet()
if request.method == 'POST':
# formset = MachineFormSet(request.POST)
# if formset.is_valid(): # All validation rules pass
line_no = request.POST['form-0-Number_of_Lines']
GetLineFormSet = formset_factory(GetLine, extra=int(line_no))
formset = GetLineFormSet()
return render_to_response('install.html', { 'formset': formset, 'action': 'step1'})
return render_to_response('install.html', { 'formset': formset, })
在安装.html模板:
^{pr2}$例如,如果“行数”=2,那么我期望下一个带有标签的表单
Name of Beamline-1:
Name of Beamline-2:
假设您希望第一个表单的结果确定第二个表单的字段数及其标签,您可能需要查看Django form wizards。但是这里有一个简单的、非表单向导(而且可能不太理想/不易维护)的方法,使用formset的
__init__
方法来修改表单标签*:在表单.py公司名称:
在视图.py公司名称:
^{2}$在网址.py公司名称:
得到_行.html公司名称:
线路_表单.html公司名称:
我之所以说这种方法可能不是最好的方法,是因为您必须验证传递给
line_form
视图的no_of_lines
(可能是>;4,因此您必须在这里执行验证并引入验证逻辑,而不是将其放在一个地方—表单)。如果您需要在第一个表单中添加一个新字段,那么您可能最终不得不修改代码。因此,我建议研究form wizards。在我认为,完成此行为的唯一方法是在将窗体集传递到模板之前调整视图中的窗体集。在
您可以迭代不同的表单和标签,并相应地更改它们的值。在
另一个可能的解决方案是将默认标签设置为“束线名称-”。 在你的模板中做一些类似的事情
相关问题 更多 >
编程相关推荐