0

Part of my business model dictates that a certain type of user cannot create more than a certain number of "things".

Let me explain with some pseudo-code:

class Thing(Model):
     owner = ForeignKey(User)

Where is the appropriate place to validate a Form, so that the user can't create the nth + 1 thing?

Salvatore Iovene
  • 2,064
  • 1
  • 17
  • 31

2 Answers2

3

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()
Timmy O'Mahony
  • 53,000
  • 18
  • 155
  • 177
1

You can consider raise an exception in one of this places:

Sample code to raise exception:

if myThing.pk is None and myThing.owner.thing_set.count() > n:
     # here raise your exception:
     raise ValidationError("Too many things!")
Community
  • 1
  • 1
dani herrera
  • 48,760
  • 8
  • 117
  • 177