[Django]-Validating number of ManyToManyField items (with intermediate model) in Django admin

5👍

You need to set the formset on the TeamPlayerInline. And override the clean method in that form set. For example:

from django.forms.models import BaseInlineFormSet

class TeamPlayerFormset(BaseInlineFormSet):
    def clean(self):
        """Check that exactly 11 players are entered."""
        super(TeamPlayerFormset, self).clean()

        if any(self.errors):
            return

        count = 0
        for cleaned_data in self.cleaned_data:
            if cleaned_data and not cleaned_data.get('DELETE', False):
                count += 1
        if count != 11:
            raise forms.ValidationError('You must enter 11 team players.')


class TeamPlayerInline(admin.TabularInline):
    model = TeamPlayer
    max_num = 11
    extra = 11
    formset = TeamPlayerFormset


class TeamAdmin(admin.ModelAdmin):
    inlines = [TeamPlayerInline]

Leave a comment