Django: How to iterate over forms and access cleared data?

What if I want to do something with my set of forms, besides saving it immediately?

How can i do this?

for form in vehicles_formset.forms: listing.id = None listing.vehicle_year = form.cleaned_data['year'] listing.vehicle_make = form.cleaned_data['make'] listing.vehicle_model = form.cleaned_data['model'] listing.vin = form.cleaned_data['vin'] listing.vehicle_runs = form.cleaned_data['runs'] listing.vehicle_convertible = form.cleaned_data['convertible'] listing.vehicle_modified = form.cleaned_data['modified'] listing.save() 

(Thus, creating multiple lists) Apparently cleaned_data does not exist. There's a bunch of things in a data dict like form-0-year , but it's pretty useless to me.

+4
source share
2 answers

Have you called vehicles_formset.is_valid() before your snippet above?

In addition, using ModelForm in your form set, you can get an instance of listing from the form by simply doing listing = form.save(commit=False)

+3
source

To continue the previous comment, after calling formset.is_valid() you can also save(commit=False) directly on the formset. This will return a list of instances that can then be individually modified and saved:

 forms = formset.save(commit=False) for form in forms: form.some_field_name = new_value form.save() 
+1
source

Source: https://habr.com/ru/post/1303528/


All Articles