Yuji 'Tomita' Tomita 的解决方案是您能找到的最好的解决方案,但假设您有一个多步骤表单并且您使用 django-formtools 应用程序,您将遇到一些必须处理的问题。谢谢 Yuji 'Tomita' Tomita,你帮了我很多 :)
forms.py
class LicmodelForm1(forms.Form):
othercolumsvalue = forms.IntegerField(min_value=0, initial=0)
class LicmodelForm2(forms.Form):
def __init__(self, *args, **kwargs):
extra_fields = kwargs.pop('extra', 0)
super(LicmodelForm2, self).__init__(*args, **kwargs)
for index in range(int(extra_fields)):
# generate extra fields in the number specified via extra_fields
self.fields['othercolums_{index}'.format(index=index)] = \
forms.CharField()
self.fields['othercolums_{index}_nullable'.format(index=index)] = \
forms.BooleanField(required=False)
对于多步骤表单,您不需要额外的字段,在此代码中,我们在第一步中使用 othercolumsvalue 字段。
views.py
class MyFormTool(SessionWizardView):
def get_template_names(self):
return [TEMPLATES[self.steps.current]]
def get_context_data(self, form, **kwargs):
context = super(MyFormTool, self).get_context_data(form=form, **kwargs)
data_step1 = self.get_cleaned_data_for_step('step1')
if self.steps.current == 'step2':
#prepare tableparts for the needLists
needList_counter = 0
for i in self.wellKnownColums:
if data_step1[i] is True:
needList_counter = needList_counter + 1
pass
#prepare tableparts for othercolums
othercolums_count = []
for i in range(0, data_step1['othercolumsvalue']):
othercolums_count.append(str(i))
context.update({'step1': data_step1})
context.update({'othercolums_count': othercolums_count})
return context
def get_form(self, step=None, data=None, files=None):
form = super(MyFormTool, self).get_form(step, data, files)
if step is None:
step = self.steps.current
if step == 'step2':
data = self.get_cleaned_data_for_step('step1')
if data['othercolumsvalue'] is not 0:
form = LicmodelForm2(self.request.POST,
extra=data['othercolumsvalue'])
return form
def done(self, form_list, **kwargs):
print('done')
return render(self.request, 'formtools_done.html', {
'form_data' : [form.cleaned_data for form in form_list],
})
通过覆盖 get_form() 和 get_context_data() 函数,您可以在表单被渲染之前覆盖它。您的模板文件也不再需要 JavaScript:
{% if step1.othercolumsvalue > 0 %}
<tr>
<th>Checkbox</th>
<th>Columname</th>
</tr>
{% for i in othercolums_count %}
<tr>
<td><center><input type="checkbox" name="othercolums_{{ i }}_nullable" id="id_othercolums_{{ i }}_nullable" /></center></td>
<td><center><input type="text" name="othercolums_{{ i }}" required id="id_othercolums_{{ i }}" /></center></td>
</tr>
{% endfor %}
{% endif %}
由于名称相同,步骤 2 中动态生成的字段也从 formtools 中重新整理。但是要到达那里,您必须解决 for-each 模板循环,如您所见:
来自 get_context_data() 函数
othercolums_count = []
for i in range(0, data_step1['othercolumsvalue']):
othercolums_count.append(str(i))