Skip to content

Instantly share code, notes, and snippets.

@DOOMer
Forked from josephabrahams/admin.py
Created April 24, 2023 21:28
Show Gist options
  • Save DOOMer/f6d625682c2f540f802038553f1192ec to your computer and use it in GitHub Desktop.
Save DOOMer/f6d625682c2f540f802038553f1192ec to your computer and use it in GitHub Desktop.
Limit number of Django model instances
from django.contrib import admin
from example.models import Example
class ExampleAdmin(admin.ModelAdmin):
"""
Don't allow addition of more than one model instance in Django admin
See: http://stackoverflow.com/a/12469482
"""
def has_add_permission(self, request):
if self.model.objects.count() > 0:
return False
else:
return True
admin.site.register(Example, ExampleAdmin)
from django.db import models
from django.core.exceptions import ValidationError
class Example(models.Model):
def clean(self):
"""
Throw ValidationError if you try to save more than one model instance
See: http://stackoverflow.com/a/6436008
"""
model = self.__class__
if (model.objects.count() > 0 and
self.id != model.objects.get().id):
raise ValidationError(
"Can only create 1 instance of %s." % model.__name__)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment