سؤال

I have a Django application that allows people to create a record. A record can contain one or more people and the form by default contains three fields to capture a person's name. One for first name, one for middle initial and one for last name. When a person is creating a record they can add additional people by clicking a plus button. The plus button adds another set of three text boxes. They can do this for as many people as they want to add.

Once they click the plus button a minus button shows up next to each row so they can remove those fields if they decide to.

What is the best way to name the text fields so that I can get all the text fields and iterate through them in the back end of the application?

I thought if I named them all the same I would get an array of names when I do:

request.POST.getlist('firstname')

However, that is not the case. Instead I get the value from the last input field with that name.

Any suggestions are appreciated.

هل كانت مفيدة؟

المحلول

I suggest you take a look at formsets instead of reinventing this one.

https://docs.djangoproject.com/en/dev/topics/forms/formsets/

from django.forms.formsets import formset_factory

FormSet = formset_factory(MyForm, extra=2)
formset = FormSet()
print formset.forms # you will see it is a collection of MyForm objects

You can dynamically add / remove formsets by modifying a the "management form" and adding the next form (you can copy {{ formset.empty_form }} and modify the IDs to be the N-th form) and there are many examples online of how to do so:

How would you make a dynamic formset in Django?
Dynamically adding a form to a Django formset with Ajax

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top