Reputation: 39
I have a django form on which i add X fields to the form on the init function
def __init__(self, *args, **kwargs):
quantity = kwargs.get('quantity')
for i in range(quantity):
self.fields['first_field_%s' % i] = forms.CharField(label='HI Number', widget=forms.TextInput(attrs={'readonly': 'readonly'}))
in my HTML template i would like to loop here aswell
{% for x in form.quantity.value|get_range %} # range filter i added
<div>
{{ form.first_field_x }}
</div>
{% endfor %}
Where x would be a number --> form.first_field_1, form.first_field_2.
If i put the number there directly i ofcourse get the bound field. I could also create the fields myself using direct html in the template
But is there a way to replace the X with a number so that the result would be a bound field?
Upvotes: 1
Views: 687
Reputation: 18002
No, you can't do that, because of the limitations of the django templating engine.
But there's a much easier solution - make "my_fields" an array, and then use an index into it, rather than the index number as part of the variable name.
def __init__(self, *args, **kwargs):
quantity = kwargs.get('quantity')
my_fields = []
for i in range(quantity):
my_fields.append(forms.CharField(label='HI Number', widget=forms.TextInput(attrs={'readonly': 'readonly'})))
self.fields['my_fields'] = my_fields
Then in the template:
{% for x in form.quantity.value|get_range %} # range filter i added
{{ form.my_fields[x] }}
{% endfor %}
Upvotes: 1