Skip to content

Instantly share code, notes, and snippets.

@josephabrahams
Created May 31, 2015 17:55
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save josephabrahams/d095822f2e09d87e97dd to your computer and use it in GitHub Desktop.
Save josephabrahams/d095822f2e09d87e97dd 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__)
@ShubhamRaiGit
Copy link

How can I display validation error in django template rather than just showing exception page

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment