You could add it to the form's clean()
method:
class ThingForm(forms.ModelForm):
def clean(self, *args, **kwargs):
cleaned_data = super(ThingForm, self).clean()
owner = cleaned_data.get("owner")
other_things_count = Things.objects.filter(owner=owner).count()
if other_things_count >= 20:
raise forms.ValidationError("Too many things!")
return cleaned_data
Alternatively you could overwrite the models save()
method, or you could create a signal that is fired on pre_save
, but neither of these will allow you tie validation messages to the form, so I think the clean()
method above is best.
EDIT If you want to exclude editing, you can check to see if the ModelForm
has an instance
, i.e. an existing object
other_things_count = Things.objects.filter(owner=owner).exclude(pk=self.instance.pk).count()