[Fixed]-Validating that between 2-5 relations exist for an object?

1👍

You can do this type of validation by overriding clean on a formset that you can inherit from:

from django.forms.models import BaseInlineFormSet


class RequiredFormSet(BaseInlineFormSet):

    def clean(self):
        for error in self.errors:
            # If any errors exist, return
            if error:
                return

        completed_formsets = 0
        for cleaned_data in self.cleaned_data:
            # only count the form if it's not being deleted
            if cleaned_data and not cleaned_data.get('DELETE', False):
                completed_formsets += 1

        if completed_formsets < 2 or completed_formsets > 5:
            raise forms.ValidationError("You must enter between "
                "2 and 5 {}".format(self.model._meta.verbose_name))

If you need to call an API with your post data after that, you can override the save, or do it in your, whatever’s best for your project.

The minimum / maximum number of forms could come from settings, or be passed in when the formset is instantiated instead of hard-coding them in this example.

Leave a comment