Salvatore Iovene
Salvatore Iovene

Reputation: 2333

Preventing a Django user from creating more than N items

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?

Upvotes: 0

Views: 98

Answers (2)

dani herrera
dani herrera

Reputation: 51765

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!")

Upvotes: 1

Timmy O'Mahony
Timmy O'Mahony

Reputation: 53998

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()

Upvotes: 3

Related Questions