Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

django

admin

In my admin for an object Chair I have a TabularInline for an arbitrary number of Desk objects. I want every Chair to always have at least one Desk object associated with it. Is there a way to make the admin interface force the user to enter at least one Desk? Like show an error if no Desk is entered?

like image 441
Ram Rachum Avatar asked Apr 13 '11 11:04

Ram Rachum


1 Answers

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)
like image 78
SuperFunkyMonkey Avatar answered Sep 29 '22 13:09

SuperFunkyMonkey