Skip to content

Instantly share code, notes, and snippets.

@mark-mishyn
Last active March 18, 2020 08:07
Show Gist options
  • Save mark-mishyn/14e4e1a761304ead87bc5c21db6eae48 to your computer and use it in GitHub Desktop.
Save mark-mishyn/14e4e1a761304ead87bc5c21db6eae48 to your computer and use it in GitHub Desktop.
Django Singleton Model and ModelAdmin
from django.db import models
from django.contrib import admin
from django.contrib.admin.options import csrf_protect_m
class SingletonModel(models.Model):
class Meta:
abstract = True
def save(self, *args, **kwargs):
self.pk = 1
super().save(*args, **kwargs)
def delete(self, *args, **kwargs):
pass # or return some reasonable validation/permission error.
@classmethod
def load(cls):
try:
return cls.objects.get(pk=1)
except cls.DoesNotExist:
raise Exception('You have to create "{}" first.'.format(cls.__name__))
class SingletonModelAdmin(admin.ModelAdmin):
"""
Class for SingletonModel subclasses to skip change list view and
hide "Add" and "Save and add another" buttons is instance already exists.
"""
@csrf_protect_m
def changelist_view(self, request, extra_context=None):
instance = self.model.objects.first()
return self.changeform_view(
request=request,
object_id=str(instance.id) if instance else None,
extra_context=extra_context)
def has_add_permission(self, request):
return not self.model.objects.exists()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment