How to limit admin input after certain number of entries in Django admin?

Viewed 331

I have been learning django for about 1 month while coming to django admin I want to limit data entries from admin not more than 5 so that when I want to display the model db on webpage be not more than 5, can you help me in this sorry if this too basic My model is

class Top5Restaurants(models.Model):
    Restaurants=models.CharField(max_length=20)

    def __str__(self):
        return( self.Restaurants)
    class Meta:
        verbose_name = 'Top 5 Restaurant'
        verbose_name_plural = 'Top_5_Restaurants'

Now I don't want more than 5 entries of Restaurants from admin interface, if admin tries entering more than 5 entries I want the entry option to blocked till admin deletes one of the entered database.

1 Answers

You can limit the number of instances a model(here Top_5_Restaurants) can have by validating the model instance that is being created/edited. Also note that the pk attribute is set to None during instance creation (vs instance updates)

class Top_5_Restaurants(models.Model):
    def clean(self):
        if (Top_5_Restaurants.objects.count() >= 5 and self.pk is None):
            raise ValidationError("Can only create five Top_5_Restaurants instances. Try editing/removing one of the existing instances.")

(A useful tip: Usually model classes are named in PascalCase and model fields in camelCase)

Related