Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Limit number of model instances to be created - django

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.

like image 440
vorpyg Avatar asked Jan 26 '10 09:01

vorpyg


People also ask

What is the purpose of __ Str__ method in Django?

str function in a django model returns a string that is exactly rendered as the display name of instances for that model. # Create your models here. This will display the objects as something always in the admin interface.

How do I create an instance of a Django model?

To create a new instance of a model, instantiate it like any other Python class: class Model (**kwargs) The keyword arguments are the names of the fields you've defined on your model. Note that instantiating a model in no way touches your database; for that, you need to save() .

How Django knows to update VS insert?

The doc says: If the object's primary key attribute is set to a value that evaluates to True (i.e. a value other than None or the empty string), Django executes an UPDATE. If the object's primary key attribute is not set or if the UPDATE didn't update anything, Django executes an INSERT link.


2 Answers

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

like image 55
ncoghlan Avatar answered Sep 21 '22 17:09

ncoghlan


If you just want to prevent users using the administrative interface from creating extra model objects you could modify the "has_add_permission" method of the model's ModelAdmin class:

# admin.py from django.contrib import admin from example.models import Example  class ExampleAdmin(admin.ModelAdmin):   def has_add_permission(self, request):     num_objects = self.model.objects.count()     if num_objects >= 1:       return False     else:       return True  admin.site.register(Example, ExampleAdmin) 

This will remove the "add" button in the administrative interface preventing users from even attempting to create more than the specified number (in this case 1). Of course programatic additions will still be possible.

like image 30
Brendan Avatar answered Sep 19 '22 17:09

Brendan