the_thor
the_thor

Reputation: 53

How limit a user to save database in django?

How do i restrict the user to save objects in db

class model_name(models.Model):
   id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=True)
   user = models.ForeignKey(User)
   foo = models.CharField(max_length=51)

i want to limit the foo only for 10 entries per user

i am using mysql as a backend

Upvotes: 0

Views: 825

Answers (1)

itzMEonTV
itzMEonTV

Reputation: 20359

You can do

class model_name(models.Model):
   id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=True)
   user = models.ForeignKey(User)
   foo = models.CharField(max_length=51)

   def save(self, *args, **kwargs):
       if self.__class__.objects.filter(user=self.user).count()>=10:
           return None
       return super(model_name, self).save(*args, **kwargs)
       #return super().save(*args, **kwargs) python3.x

You can do the same thing if you are using forms by updating Form.clean method

def clean(self):
    super(MyForm, self).clean()
    if model_name.objects.filter(user=self.cleaned_data['user']).count()>=10:
           raise forms.ValidationError("You have exceeded limit.")

Upvotes: 4

Related Questions