Created
July 31, 2020 10:34
-
-
Save maxpoletaev/80ebe2d75d29438b306bed6315ef3c25 to your computer and use it in GitHub Desktop.
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.contrib import admin | |
from django.shortcuts import redirect | |
class SingletonModel(models.Model): | |
class Meta: | |
abstract = True | |
def save(self, *args, **kwargs): | |
self.pk = 1 | |
super().save(*args, **kwargs) | |
class SingletonModelAdmin(admin.ModelAdmin): | |
actions = None | |
def has_delete_permission(self, request, obj=None): | |
return False | |
def changelist_view(self, request, *args, **kwargs): | |
app_label, model_name = ( | |
self.model._meta.app_label, | |
self.model._meta.model_name, | |
) | |
try: | |
singleton = self.get_queryset(request).get() | |
except self.model.MultipleObjectsReturned: | |
return super().changelist_view(request, *args, **kwargs) | |
except self.model.DoesNotExist: | |
return redirect(f"admin:{app_label}_{model_name}_add") | |
return redirect(f"admin:{app_label}_{model_name}_change", singleton.id) | |
class SingletonInlineMixin: | |
max_num = 1 | |
min_num = 1 | |
def has_delete_permission(self, request, obj=None): | |
return False |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment