如何获得附加的DJango表单数据



如何获取附加表单的所有行数据?我有一个表单,每行有5个数字,并附加了一些由用户选择的"N"行数。

形式:

class locker(forms.Form):
num0 = forms.IntegerField(label='', min_value=1, max_value=25, required=True)
num1 = forms.IntegerField(label='', min_value=1, max_value=25, required=True)
num2 = forms.IntegerField(label='', min_value=1, max_value=25, required=True)
num3 = forms.IntegerField(label='', min_value=1, max_value=25, required=True)
num4 = forms.IntegerField(label='', min_value=1, max_value=25, required=True)

视图:

# Render form
...
count = 3
newForm = locker()
context.update({ 'locker': newForm, 'lockerCount': range(count) })
...

模板:

# Display form
...
<div class="lockers">
<form name="longForm" action="" method="post">
{% csrf_token %}
{% for i in lockerCount %}
{{ locker }}<br />
{% endfor %}
<br />
<input type="submit" value="submit" class="small-button">
</form>
</div>
...

我尝试过从谷歌上搜索的各种方法,最接近的是:

...
data = form.cleaned_data.items()
for q in data:
...

但它只得到最后一行数字。看着控制台,我确实看到了所有的数据(如下(。我正在尝试获取表单的所有行,每行包含5组整数。请帮忙。

[29/Sep/2022 23:19:42] "POST /main/ HTTP/1.1" 200 10113
[29/Sep/2022 23:20:43] "GET /main/?csrfmiddlewaretoken=w3YIsEf1Af2hX4IRfPIVShZCdUjh9EEnbu2o8UGbI8XFbcTif6f1FlviC3KoHDM8&num0=7&num1=6&num2=21&num3=5&num4=11&num0=22&num1=4&num2=6&num3=19&num4=10&num0=9&num1=14&num2=20&num3=3&num4=25 HTTP/1.1" 200 7687

弄明白了。我把表格涂错了。使用"formset_factory"创建表单集解决了问题。

视图:

# Render form
...
count = 3
lockerSet = formset_factory(locker, extra=count, max_num=10)
context.update({ 'lockerSet': lockerSet })
...

模板:

# Display form
...
<div class="lockers">
<form name="longForm" action="" method="post">
{% csrf_token %}
{{ lockerSet.management_form }}
{% for form in lockerSet %}
{{ form }}<br />
{% endfor %}
<br />
<input type="submit" value="submit" class="small-button">
</form>
</div>
...

然后我就可以访问这样的所有数据:

lockerSet = formset_factory(locker, extra=count, max_num=10)
formSet = formset(request.POST)
if formSet.is_valid():
for form in formSet:
m0 = form.cleaned_data['num0']
m1 = form.cleaned.data['num1']
...

相关内容

  • 没有找到相关文章

最新更新