[Django] 권한 부여

sudog·2023년 10월 5일
0

Django

목록 보기
13/13

장고에서 특정 사용자에게 권한을 주고 싶은 경우가 있다. 가령, 커뮤니티에서 모든 글을 삭제하거나 수정할 권한을 가진 관리자 유저가 필요한 경우가 있을 수 있다.

이런 경우, 다음과 같은 방법을 사용해서 권한을 부여할 수 있다.

  1. 커스텀 유저 모델에서 PermissionsMixin을 상속받는다. 이제 유저 모델에 그룹과 권한을 추가할 수 있다.
  2. permission객체를 생성하고 이 객체를 유저 객체에 할당한다.
  3. 권한이 필요한 경우, 유저 모델의 has_perm을 사용해 해당 권한을 확인한다.

예제 코드는 다음과 같다.

from django.contrib.auth.models import Permission
from django.contrib.contenttypes.models import ContentType
from .models import Articles

content_type = ContentType.objects.get_for_model(Articles)
permission = Permission.objects.create(
    codename='delete_all_articles',
    name='Can Delete All Articles',
    content_type=content_type_of_article_model
)

user.user_permissions.add(permission)

if user.has_perm('myapp.can_delete_mymodel'):
	# delete
else:
	# denied

여기서 codename은 실제로 이 권한의 이름이고, name은 이 권한에 대한 설명이다. 그렇다면 content_type은 정체가 뭘까? 이것은 모델에 대한 참조로, 이것을 이용해서 해당 모델에 대한 권한이라는 것을 명시한다. 이제 게시글을 삭제하기 전에 해당 유저가 삭제 권한을 가지고 있는지 확인하면 된다.

profile
안녕하세요

0개의 댓글