开发者

Django: How to iterate over formsets and access cleaned data?

开发者 https://www.devze.com 2022-12-22 03:14 出处:网络
What if I want to do something with my formset other than immediately saving it? How can I do this? for form in vehicles_formset.forms:

What if I want to do something with my formset other than immediately saving it?

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.clean开发者_StackOverflow中文版ed_data['convertible']
            listing.vehicle_modified = form.cleaned_data['modified']
            listing.save()

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


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

Additionally, using a ModelForm in your formset will allow you to get a listing instance from the form by simply doing listing = form.save(commit=False)


Just to further the previous comment, once formset.is_valid() is called, you can also do save(commit=False) directly on the formset. This will return a list of the instances, which can then be individually modified and then saved:

forms = formset.save(commit=False)
for form in forms:
    form.some_field_name = new_value
    form.save()
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号