简体   繁体   中英

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?

You have to generate two dicts and use them to initiate two PersonForm s. 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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM