如果我想使用我的formset 其他做什么比立即保存它怎么办?
我该怎么做?
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()
(因此创建多个列表)显然cleaned_data
不存在。 data
dict中有很多东西,比如form-0-year
,但对我来说这样没用。
答案 0 :(得分:3)
您是否在上面的代码段之前调用了vehicles_formset.is_valid()
?
此外,在您的表单集中使用ModelForm,您只需执行listing = form.save(commit=False)
答案 1 :(得分:1)
为了进一步推广上一条评论,调用formset.is_valid()
后,您还可以直接在表单集上执行save(commit=False)
。这将返回实例列表,然后可以单独修改然后保存:
forms = formset.save(commit=False)
for form in forms:
form.some_field_name = new_value
form.save()