Django: Forcing admin users to enter at least one item in TabularInline

后端 未结 3 1095
死守一世寂寞
死守一世寂寞 2021-02-04 13:36

In my admin for an object Chair I have a TabularInline for an arbitrary number of Desk objects. I want every Chair to always

3条回答
  •  清酒与你
    2021-02-04 14:34

    Using akaihola's answer, here is a more complete example:

    Add this to your forms.py:

    from django import forms
    from django.forms.models import BaseInlineFormSet
    
    class AtLeastOneRequiredInlineFormSet(BaseInlineFormSet):
    
        def clean(self):
            """Check that at least one service has been entered."""
            super(AtLeastOneRequiredInlineFormSet, self).clean()
            if any(self.errors):
                return
            if not any(cleaned_data and not cleaned_data.get('DELETE', False)
                for cleaned_data in self.cleaned_data):
                raise forms.ValidationError('At least one item required.')
    

    And then, in your admin.py:

    class DeskInline(admin.TabularInline):
        model = Desk
        formset = AtLeastOneRequiredInlineFormSet
    
    class ChairAdmin(admin.ModelAdmin):
        inlines = [DeskInline,]
    
    admin.site.register(Chair, ChairAdmin)
    

提交回复
热议问题