0

Inline 内のオブジェクトの ForeignKey 関連付けをクリアできるようにしたいのですが、実際にそのオブジェクトを削除することはできません。Django の検証を使用してオブジェクトが削除されないようにするにはどうすればよいですか?

4

1 に答える 1

0
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]
于 2012-09-26T18:25:40.927 に答える