How do you get all row data of the forms that were appended? I have a form with 5 numbers per row, and some 'N' number of rows that are selected by the user is appended.
Form:
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)
View:
# Render form
...
count = 3
newForm = locker()
context.update({ 'locker': newForm, 'lockerCount': range(count) })
...
Template:
# Display form
...
<div >
<form name="longForm" action="" method="post">
{% csrf_token %}
{% for i in lockerCount %}
{{ locker }}<br />
{% endfor %}
<br />
<input type="submit" value="submit" >
</form>
</div>
...
I've tried various methods searched from google, and the closest I got was:
...
data = form.cleaned_data.items()
for q in data:
...
but it's getting only the last row of numbers. Looking at the console, I do see all the data (below). I'm trying to get all rows of the form, each row containing 5 sets of integers. Please help.
[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
CodePudding user response:
Got it figured out. I was rendering the form in wrong way. Using the 'formset_factory' to create the formset solved it.
View:
# Render form
...
count = 3
lockerSet = formset_factory(locker, extra=count, max_num=10)
context.update({ 'lockerSet': lockerSet })
...
Template:
# Display form
...
<div >
<form name="longForm" action="" method="post">
{% csrf_token %}
{{ lockerSet.management_form }}
{% for form in lockerSet %}
{{ form }}<br />
{% endfor %}
<br />
<input type="submit" value="submit" >
</form>
</div>
...
Then I was able to access all the data like this:
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']
...