You can override the clean method on your BlogSite model BlogSite
from django.core.exceptions import ValidationError class BlogSite(models.Model): blog_owner = models.ForeignKey(User) site_name = models.CharField(max_length=300) regions = models.ManyToManyField('Region', blank=True, null=True) def clean(self, *args, **kwargs): if self.regions.count() > 3: raise ValidationError("You can't assign more than three regions") super(BlogSite, self).clean(*args, **kwargs)
And if you use django ModelForm, this error will appear in the form of non_field_errors.
EDIT:
M2m fields are saved after saving the model, so the above code will not work, the correct way to use the m2m_changed signal m2m_changed :
from django.db.models.signals import m2m_changed from django.core.exceptions import ValidationError def regions_changed(sender, **kwargs): if kwargs['instance'].regions.count() > 3: raise ValidationError("You can't assign more than three regions") m2m_changed.connect(regions_changed, sender=BlogSite.regions.through)
Try it to work for me.
Mounir
source share