📢 공지사항
home

Decorator를 이용한 코드 간소화

수강계획
2022/01/12
번호
28
복습여부
수강여부
수강일
2022/01/13
속성
Decorator : 어떤 function 앞뒤에 붙어서 꾸며주는 기능
class 안에 있는 메서드에서는 @login_required 한다고 적용되지 않음
@method_decorator() : 일반 function에 사용하는 decorator를 메서드에 사용할 수 있도록 변환해줌
account 앱 내부에서 decorators.py 파일 생성
메서드 데코레이터는 리스트로 작성해서 가져올 수 있음
from django.contrib.auth.models import User from django.http import HttpResponseForbidden def account_ownership_required(func): def decorated(request, *args, **kwargs): user = User.objects.get(pk=kwargs['pk']) if not user == request.user: return HttpResponseForbidden() return func(request, *args, **kwargs) return decorated
Python
복사
decorators.py
from django.contrib.auth.decorators import login_required from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User from django.http import HttpResponse, HttpResponseRedirect, HttpResponseForbidden from django.shortcuts import render # Create your views here. from django.urls import reverse, reverse_lazy from django.utils.decorators import method_decorator from django.views.generic import CreateView, DetailView, UpdateView, DeleteView from accountapp.decorators import account_ownership_required from accountapp.forms import AccountUpdateForm from accountapp.models import HelloWorld has_ownership = [account_ownership_required, login_required] @login_required def hello_world(request): # if request.user.is_authenticated: if request.method == "POST": temp = request.POST.get('hello_world_input') new_hello_world = HelloWorld() new_hello_world.text = temp new_hello_world.save() hello_world_list = HelloWorld.objects.all() return HttpResponseRedirect(reverse('accountapp:hello_world')) else: hello_world_list = HelloWorld.objects.all() return render(request, 'accountapp/hello_world.html', context={'hello_world_list': hello_world_list}) # else: # return HttpResponseRedirect(reverse('accountapp:login')) class AccountCreateView(CreateView): model = User form_class = UserCreationForm success_url = reverse_lazy('accountapp:hello_world') template_name = 'accountapp/create.html' class AccountDetailView(DetailView): model = User context_object_name = 'target_user' template_name = 'accountapp/detail.html' @method_decorator(has_ownership, 'get') @method_decorator(has_ownership, 'post') class AccountUpdateView(UpdateView): model = User context_object_name = 'target_user' form_class = AccountUpdateForm success_url = reverse_lazy('accountapp:hello_world') template_name = 'accountapp/update.html' @method_decorator(has_ownership, 'get') @method_decorator(has_ownership, 'post') class AccountDeleteView(DeleteView): model = User context_object_name = 'target_user' success_url = reverse_lazy('accountapp:login') template_name = 'accountapp/delete.html'
Python
복사
views.py