formset删除内联实例

时间:2016-04-13 07:34:07

标签: django python-2.7 django-models django-forms django-admin

已确定我需要从表单集中删除的对象。

America/Cancun  CST CST (standard)
America/Cancun  CDT CDT (daylight savings)
--
America/Chicago CST Central Standard Time (standard)
America/Chicago CDT Central Daylight Time (daylight savings)
--
America/Havana  CST CST (standard)
America/Havana  CDT CDT (daylight savings)
--
America/Menominee   CST CST (standard)
America/Menominee   CDT CDT (daylight savings)
America/Merida  CST CST (standard)
America/Merida  CDT CDT (daylight savings)
America/Mexico_City CST CST (standard)
America/Mexico_City CDT CDT (daylight savings)
--
America/Monterrey   CST CST (standard)
America/Monterrey   CDT CDT (daylight savings)
--
America/North_Dakota/Center CST CST (standard)
America/North_Dakota/Center CDT CDT (daylight savings)
--
America/Rainy_River CST CST (standard)
America/Rainy_River CDT CDT (daylight savings)
America/Rankin_Inlet    CST CST (standard)
America/Rankin_Inlet    CDT CDT (daylight savings)
--
America/Winnipeg    CST CST (standard)
America/Winnipeg    CDT CDT (daylight savings)

以错误

结束
def save_formset(self, request, form, formset, change):
        instances = formset.save(commit=False)
        for instance in instances:
            ......
        if formset.deleted_forms:
            for obj in formset.deleted_forms:
               obj.delete() //here is the issue

这就是formset.deleted_forms

*** AttributeError: 'ActivitiesForm' object has no attribute 'delete'

这里出了什么问题?基本上我试图删除管理员选择的内联条目

2 个答案:

答案 0 :(得分:4)

如果您使用的是模型表单集,则应该遍历deleted_objects,而不是deleted_forms。有关详细信息,请参阅the docs

for obj in formset.deleted_objects:
    obj.delete()

请注意,在Django 1.7(release notes)之前,您不需要手动删除对象。调用save()时删除了对象,即使使用commit=False

答案 1 :(得分:0)

在 Django >=1.11 中,您可以覆盖表单集上的删除:

class YourInlineFormset(BaseInlineFormSet):

    def delete_existing(self, obj, commit=True):
        if commit:
            do_delete_it_your_way()