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.
I would override create() method on default manager, but as stated above, this won't guarantee anything in multi-threaded environment.
You can do something like this, from the Django docs:
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:
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.
I wanted to do something similar myself, and found that Django's model validation provided a convenient hook for enforcement:
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).
@ncoghlan your solution is working fine, but not very user-friendly: the user has access to the creation form and will think he/she can use it, even though he/she will never be able to save it.
It's actually possible to combine it with Brendan's solution, which will hide the 'Add' button. Using Mixins for easy reuse: