Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django: create HTML input array using a django form

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...

like image 537
Brant Avatar asked Mar 10 '10 19:03

Brant


2 Answers

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 %}
like image 113
Dan Breen Avatar answered Sep 19 '22 07:09

Dan Breen


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

like image 42
Brant Avatar answered Sep 19 '22 07:09

Brant