zyeek
zyeek

Reputation: 1287

DJANGO: request.POST.getlist() into ModelForm

I have been searching online, but have not found anything that would help solve this issue.

Lets say in a view we receive some POST info. We have a ModelForm containing an int and char field. The POST contains a query dict of names and ages.

{ 'name': ['John', 'Doe'], 'age': [22, 24] }.

How can I get this post info into a ModelForm nicely. I do

PersonForm(request.POST)

which only gets 1 of the set of POST info.

Is there a better solution, rather than just getting a list of the POST fields and putting them into the fields?

Upvotes: 1

Views: 5488

Answers (1)

catavaran
catavaran

Reputation: 45575

You have to generate two dicts and use them to initiate two PersonForms. Something like this:

name_age_pairs = zip(request.POST.getlist('name'), request.POST.getlist('age'))
data_dicts = [{'name': name, 'age': age} for name, age in name_age_pairs]
for data in data_dicts:
    form = PersonForm(data)
    form.save()

Upvotes: 3

Related Questions