Skip to content

Instantly share code, notes, and snippets.

@tochimclaren
Forked from sanbartels/admin.py
Created September 13, 2020 15:22
Show Gist options
  • Save tochimclaren/8145fe29b5d817fd5b573adec8397512 to your computer and use it in GitHub Desktop.
Save tochimclaren/8145fe29b5d817fd5b573adec8397512 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