I am trying to automate the creation of something like this:
<input type='text' name='asdf[]' />
<input type='text' name='asdf[]' />
<input type='text' name='asdf[]' />
By cycling through a range in the form. I've been trying things like this, along with several other variations:
# in a model class
for i in range(1, prim+1):
self.fields['asdf'] = forms.CharField(label=i)
# in the template
<form action='#' method='post'>
{{form.as_p}}
</form>
But I haven't had any luck though.
How can I go about automating an array of inputs?
** edit ** To clarify, eventually I need to be able to access the fields in the template like this:
{% for input in form.fields.asdf %}
{{input}}
{% endfor %}
Which would then hopefully get me the original input list shown above...
Jacob Kaplan-Moss (co-author of Django) recently posted a great article for handling dynamic forms, which should solve your problem in a preferred way: http://jacobian.org/writing/dynamic-form-generation/
He's using the same method that Felix suggests, but it's worth reading the whole article to get a better grasp on the concept.
Using the asdf[]
technique is sloppy, because then you have to deal with ordering. It's also not the standard practice.
Edit:
To handle the situation where you need to detect when you hit these dynamic fields:
{% for input in form.fields %}
{% ifequal input.label 'asdf' %}
{{ forloop.counter }}: {{input}}<br />
{% endifequal %}
{% endfor %}
It looks like I can do what I need to do by breaking the form into multiple formsets...
http://docs.djangoproject.com/en/dev/topics/forms/formsets/#topics-forms-formsets
Then, I should be able to access each formset individually from the template, wrapping all of them into one
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With