Limit number of model instances to be created - django
django, django-admin, django-models
Solution
I wanted to do something similar myself, and found that Django's model validation provided a convenient hook for enforcement:
from django.db import models
from django.core.exceptions import ValidationError
def validate_only_one_instance(obj):
model = obj.__class__
if (model.objects.count() > 0 and
obj.id != model.objects.get().id):
raise ValidationError("Can only create 1 %s instance" % model.__name__)
class Example(models.Model):
def clean(self):
validate_only_one_instance(self)
That not only prevents the creation of new instances, but the Django admin UI will actually report that the creation failed and the reason was "Can only create 1 Example instance"(whereas the early return approach in the docs gives no indication as to why the save didn't work).
Problem
I have model from which I only want to create one instance, and no more instances should be allowed. Is this possible? I've got a feeling that I've seen this done somewhere, but unfortunately I'm unable to locate it. EDIT: I need this for a stupidly simple CMS. I have an abstract class for which FrontPage and Page classes inherits. I only want to be able to create one frontpage object. The difference between the FrontPage object and the Page objects are that they're supposed to have slightly different fields and templates, and as mentioned only one FrontPage is to be created.