Web개발/DJANGO

Django Permission

별냥이 2020. 6. 13. 19:44
반응형

참고 : developer.mozilla.org/en-US/docs/Learn/Server-side/Django/Authentication

 

Django Tutorial Part 8: User authentication and permissions

Excellent work — you've now created a website that library members can log in into and view their own content and that librarians (with the correct permission) can use to view all loaned books and their borrowers. At the moment we're still just viewing c

developer.mozilla.org

 

1.view.py에서의 처리

 

1.1. 함수 view의 경우

 

from django.contrib.auth.decorators import login_required

@login_required

def 함수

    #이하 함수view내용

 

 

1.2.클래스 view의 경우

from django.contrib.auth.mixins import LoginRequiredMixin

class MyView(LoginRequriedMixin, View):

    #이하 class view내용

 

2. Permission처리

2.1. Model에 Permission추가

    models.py의 해당 모델의 Meta항목에 다음과 같이 입력

    class Meta:

         ...

         permissions = (('can_do_soemthing', "뭔가 할수 있는 권한"),)

 

    #위같이 입력하고 migration을 하면 admin페이지에서 permission이 추가됨

    #각 tuple의 끝에 쉽표( , )를 빼놓으면 에러남.

 

2.2. View에서 Permission처리

2.2.1. 함수의 경우

     from django.contrib.auth.decorators import permission_required

     @permission_required('App이름.can_do_something')

     def my_view(request)

              #이하 함수내용

 

2.2.2. class 경우

     from django.contrib.auth.mixins import PermissionRequiredMixin

     class MyView(PermissionRequiredMixin, View):

          permission_required = 'App이름.can_do_something'

          #이하 class내용

 

3. template에서의 처리

 

{% if user.is_authenticated %}  : 인증여부 확인

{% if user.get_username %} : 사용자 이름 불러오기

{% if user.is_staff %} : staff그룹인지 확인(django built-in 그룹이므로 생성할 필요없음)

{% if perms.App이름.can_do_soemthing %} : 해당 권한 보유여부 확인

 

4.기타

LOGIN_REDIRECT_URL = '/' : 이 문구를 setting.py에 넣으면 로그인시 루트페이지로 이동

 

 

반응형