To dynamically add field to a form with Python Django, we can add the form with a for loop.
For instance, we write
class MyForm(forms.Form):
original_field = forms.CharField()
extra_field_count = forms.CharField(widget=forms.HiddenInput())
def __init__(self, *args, **kwargs):
extra_fields = kwargs.pop('extra', 0)
super(MyForm, self).__init__(*args, **kwargs)
self.fields['extra_field_count'].initial = extra_fields
for index in range(int(extra_fields)):
self.fields['extra_field_{index}'.format(index=index)] = \
forms.CharField()
to create the MyForm
form that has a for loop in the __init__
method that creates CharField
s and add them into the self.fields
dictionary dynamically.
Then in our view, we can use the form with
def myview(request):
if request.method == 'POST':
form = MyForm(request.POST, extra=request.POST.get('extra_field_count'))
if form.is_valid():
print "valid!"
else:
form = MyForm()
return render(request, "template", { 'form': form })
We set the extra
argument to a list we get from request.POST.get
.
Then we render the template for the view with
<form>
<div id="forms">
{{ form.as_p }}
</div>
<button id="add-another">add another</button>
<input type="submit" />
</form>