I’m using python and django and I would like to use a variable I entered in a previous input, to iterate over creating multiple other input fields.
This is the part in the Django template where I ask the number I would like to use in the iteration:
<form method="GET">
<label for="grondstoffen_count" style="font-family: Oswald, sans-serif;">Give how many products were delivered:</label>
<input type="number" name="grondstoffen_count" id="grondstoffen_count" min="0" required>
<button type="submit" name="submit_count">Bevestig</button>
</form>
This is the part my views.py where I generate a string of the sequence up to the input number. When I have the string I return it to the Django template:
elif 'submit_count' in self.request.GET:
grondstoffen_count = int(self.request.GET.get('grondstoffen_count', 0))
volgordelijst = ""
for i in range(1, grondstoffen_count + 1):
volgordelijst += str(i)
print(type(volgordelijst)) # string
print(volgordelijst) # when grondstoffen_count is 5 then this gives "12345"
return render(self.request, 'Ano_app/BehandelNieuweVoorraad.html', {'volgordelijst': volgordelijst})
In the template I receive the ‘volgordelijst’ (so I don’t think it’s a problem with giving the variable from the view to the template because the name is automatically suggested) and I would like to use that variable for the loop. I would like to have as many input fields as the number in the original input but when I run the server it doesn’t show a single one. When I change ‘volgordelijst’ by “12345” it works perfectly. I also have other lists I give to the template and there I have no problem whatsoever to iterate:
<form method='GET'>
{% for i in volgordelijst %}
{% with key="query_grondstof"|add:i|add:"hoeveelheid" %}
<div style="display: inline-block; margin-right: 10px;">
<h4 style="font-family: Oswald, sans-serif;">Grondstof {{ i }} naam:</h4>
<input list="grondstof{{ i }}datalist" name="query_grondstof{{ i }}naam" id="grondstof{{ i }}" required>
<datalist id="grondstof{{ i }}datalist">
{% for option in grondstof_options %}
<option value="{{ option }}">
{% endfor %}
</datalist>
</div>
<div style="display: inline-block; margin-right: 10px;">
<h4 style="font-family: Oswald, sans-serif;">Grondstof {{ i }} hoeveelheid in ton:</h4>
<input type='number' step="0.01" name='{{ key }}' value='{{ request.GET.key }}' min="0" required>
</div>
<br>
{% endwith %}
{% endfor %}
</form>
Greg Degoeiegast is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.