模型 Fomset 和删除

Model Fomset and deletion

我创建了一个模型集使用符号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 的每个实例,并在将实例的帐户 属性 设置为上面保存的帐户后保存它.但是当我点击模板上的表单集中每个表单的删除按钮时,表单正常发布但没有删除。这是为什么?

编辑:将代码更改为 if

account=form.save()
formset.save()

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

您可以遍历 formset.deleted_forms:

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

作为替代方案,您可以在 cleaned_data:

中检查 DELETE
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()