模型Fomset和删除

时间:2015-02-13 14:39:32

标签: django modelform formset

我创建了一个modelformset usign modelformset_factory

formfactory = modelformset_factory(HasJobs, form=HasJobsModelForm, can_delete=True)
formset = modelformset_factory(request.POST or None)

if request.method == "POST":
    form = AccountModelForm(request.POST, instance=account)
    account = form.save()
    for job_form in formset:
        instance = job_form.save(commit=False)
        instance.account = account
        instance.save()

换句话说,我使用每个模型表单创建一个帐户,然后使用表单集中的每个表单创建每个HasJob实例,并在将实例的帐户属性设置为上述保存的帐户后保存。但是当我单击模板上的formset中每个表单的删除按钮时,表单正常发布但没有删除。那是为什么?

编辑:如果

将代码更改为此内部
account=form.save()
formset.save()

导致删除实例但在创建新实例时不保存

1 个答案:

答案 0 :(得分:1)

您可以遍历formset.deleted_forms

for form in formset.deleted_forms:
    if form.instance.pk:
        form.instance.delete()

作为替代方案,您可以在DELETE

中查看cleaned_data密钥
for job_form in formset:
    if job_form.is_valid():
        if job_form.cleaned_data.get('DELETE') and job_form.instance.pk:
            job_form.instance.delete()
        else:
            instance = job_form.save(commit=False)
            instance.account = account
            instance.save()