【问题标题】:How do I prevent the deletion of an object in an InlineForm Validation?如何防止删除 InlineForm 验证中的对象?
【发布时间】:2012-09-26 18:23:38
【问题描述】:

我希望能够清除内联对象的 ForeignKey 关联,但不能真正删除该对象。如何使用 Django 的验证来防止对象被删除?

【问题讨论】:

    标签: django django-forms


    【解决方案1】:
    class LocationInlineFormset(forms.models.BaseInlineFormSet):
        def clean(self):
            for form in self.forms:
                try:
                    if form.cleaned_data:
                        loc = Location.objects.filter( /* filter to find the location being edited/added */ )
                        if loc:#This validation only matters if we're not adding a new location
                            loc = loc[0]
                            if form.cleaned_data['DELETE']:
                                # Clear the Foreign Key Association
                                loc.strain = None
                                loc.save()
                                # Prevent Deletion
                                form.data[form.add_prefix('DELETE')] = 'false'
                except AttributeError:
                    # annoyingly, if a subform is invalid Django explicity 
                    # raises an AttributeError for cleaned_data
                    pass
    
    class LocationInline(admin.TabularInline):
        formset = LocationInlineFormset
        model = Location
        extra = 3
        max_num = 3
        can_delete = True
    
    class StrainAdmin(MyAdmin):
        inlines = [LocationInline]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-08
      • 2020-06-09
      相关资源
      最近更新 更多