防止Django用户创建超过N个项目

时间:2012-08-11 14:25:38

标签: django validation

我的商业模式的一部分规定某种类型的用户不能创造超过一定数量的“事物”。

让我用一些伪代码解释一下:

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

验证Form的适当位置在哪里,以便用户无法创建nth + 1内容?

2 个答案:

答案 0 :(得分:3)

您可以将其添加到表单的clean()方法:

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

或者你可以overwrite the models save() method,或者你可以创建一个signal that is fired on pre_save,但这些都不允许你将验证消息绑定到表单,所以我认为上面的clean()方法是最好的。

编辑如果您要排除编辑,可以查看ModelForm是否有instance,即现有对象

other_things_count = Things.objects.filter(owner=owner).exclude(pk=self.instance.pk).count()

答案 1 :(得分:1)

您可以考虑在以下某个位置引发异常:

引发异常的示例代码:

if myThing.pk is None and myThing.owner.thing_set.count() > n:
     # here raise your exception:
     raise ValidationError("Too many things!")