-
-
Save sanbartels/b12e27934d1f68ea0a2a6264c497b735 to your computer and use it in GitHub Desktop.
Limit number of Django model instances
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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