Skip to content

Instantly share code, notes, and snippets.

@sanbartels
Forked from josephabrahams/admin.py
Created October 13, 2016 21:08
Show Gist options
  • Save sanbartels/b12e27934d1f68ea0a2a6264c497b735 to your computer and use it in GitHub Desktop.
Save sanbartels/b12e27934d1f68ea0a2a6264c497b735 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