前回に引き続きDjangoのパーミッションについて勉強する。
今回はカスタムパーミッション(add・change・delete・view以外のパーミッション)を作成してみる。
公式ドキュメントは以下
docs.djangoproject.com
モデルクラスのMetaクラスにカスタムパーミッションを定義する。
公式ドキュメントを参考にしながら、QuestionモデルのMetaに「copy_question」というパーミッションを追加する。
class Question(models.Model): question_text = models.CharField(max_length=200) pub_date = models.DateTimeField("date published") # 以下を追加 class Meta: permissions = [ ("copy_question", "Can copy question"), ]
マイグレーションを実行する。
$ python manage.py migrate Migrations for 'polls': polls/migrations/0002_auto_20200514_1423.py - Change Meta options on question $ python manage.py migrate Operations to perform: Apply all migrations: admin, auth, contenttypes, polls, sessions Running migrations: Applying contenttypes.0001_initial... OK Applying auth.0001_initial... OK Applying admin.0001_initial... OK Applying admin.0002_logentry_remove_auto_add... OK Applying admin.0003_logentry_add_action_flag_choices... OK Applying contenttypes.0002_remove_content_type_name... OK Applying auth.0002_alter_permission_name_max_length... OK Applying auth.0003_alter_user_email_max_length... OK Applying auth.0004_alter_user_username_opts... OK Applying auth.0005_alter_user_last_login_null... OK Applying auth.0006_require_contenttypes_0002... OK Applying auth.0007_alter_validators_add_error_messages... OK Applying auth.0008_alter_user_username_max_length... OK Applying auth.0009_alter_user_last_name_max_length... OK Applying auth.0010_alter_group_name_max_length... OK Applying auth.0011_update_proxy_permissions... OK Applying polls.0001_initial... OK Applying polls.0002_auto_20200514_1423... OK Applying sessions.0001_initial... OK $
SQLite内のデータを確認する。
sqlite> select * from auth_permission where content_type_id = (select id from django_content_type where model = 'question'); 1|1|add_question|Can add question 2|1|change_question|Can change question 3|1|delete_question|Can delete question 4|1|view_question|Can view question 5|1|copy_question|Can copy question sqlite>
→ 「copy_question」が作成されていることを確認できる。
管理画面を確認する。
→ 「copy_question」が選択できるようになっていることが確認できる。