首先,我一般是从数据库中创建我的表单。这是我的代码:
模板:
{% block wizard_form_content %}
<div id="alt-list">
<div id="alt-list-header">
<h4>Grids List</h4>
</div>
<div id="alt-list-data" class="container">
{% for grid in data.grids %}
<input type="checkbox" name="{{ grid.name }}" id="id_{{ grid.name }}" tabindex="{{ forloop.counter}}" size="30">{{ grid.name }}<br>
{% endfor %}
</div>
</div>
{% if wizard.form.errors %}
<div class="form-errors-wrapper">
<div class="error">
{% for error in wizard.form.non_field_errors %}
<p>{{ error }}</p>
{% endfor %}
</div>
</div>
{% endif %}
<input type="hidden" name="num-grids" value="{{ data.grids|length }}" id="num-grids" />
<input type="hidden" name="user" value="{{ data.user }}" id="user" />
{% endblock wizard_form_content %}
这是相应的形式:
class WhichGridsForm(forms.Form):
# Override the initialize in order to dynamically add fields to the form in order to be saved,
# the fields are saved only when the user selects 'Next Step'.
def __init__(self, *args, **kwargs):
super(WhichGridsForm, self).__init__(*args, **kwargs)
if len(self.data) > 0:
self.num_grids = self.data['num-grids']
user_name = self.data['user']
user1 = User.objects.filter(username=user_name)
gridtype = Grid.GridType.USER_GRID
templateData = ShowGridsData()
templateData.grids = Grid.objects.filter(user=user1, grid_type=gridtype)
for grid in templateData.grids:
gridName = grid.name
# Every time, alternative fields are added with the name 'alternative..', and this because django
# always adds '1-' % (where 1 the number of the step with zero index) prefix in the name,
# with this the names are kept always the same.
self.fields[gridName] = forms.BooleanField(required=False)
请记住,这是第 2 步,当我尝试使用这行代码从第 3 步获取第 2 步数据时:
elif self.steps.step1 == 3:
try:
grids_data = self.get_cleaned_data_for_step('1')
print grids_data
即使我检查了所有字段,所有字段似乎都是“错误的”。
{u'Cars': False, u'grid11': False, u'deneme11': False, u'asd': False}
你知道为什么会发生这种情况吗?
编辑:
但是如果我在“完成”方法中打印表单字段,我会得到正确的结果:
<MultiValueDict: {u'num-grids': [u'4'], u'deneme11': [u'on'], u'Cars': [u'on'], u'composite_wizard-current_step': [u'1'], u'grid11': [u'on'], u'user': [u'muratayan'], u'asd': [u'on'], u'csrfmiddlewaretoken': [u'JYIT5gHs35ZBvk7rCITfpMIPrFleUYXF']}>