8
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Djangoの管理画面でデータを一つだけしか登録できなくする方法

Last updated at Posted at 2016-08-26

目的

全体で1つだけでいいデータ(例えば設定など)を保存したい

方法

Model

models.py
from django.db import models

class Setting(models.Model):
	pass

Admin

admin.py
from django.contrib import admin
from .models import Setting

class SettingAdmin(admin.ModelAdmin):
	def has_add_permission(self, request):
        # 設定を1つだけしか登録できないようにする
        count = Setting.objects.all().count()
        if count == 0:
            return True
        return False

    def has_delete_permission(self, request, obj=None):
        # 設定を削除できないようにする
        return False
        
admin.site.register(Setting,SettingAdmin)

has_add_permissionをoverrideすることで特定の数だけの登録やrequest.userからユーザーごとに追加できるできないを制御できると思います。
同様にhas_delete_permissionをoverrideして削除の制御が可能です。

8
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
8
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?