코드 가독성을 높이기 위해 decorator를 이용해보자
함수 decorator
@login_required
def hello_world(request):
if request.method == "POST":
text = request.POST.get('hello_world_input')
new_hello_world = HelloWorld()
new_hello_world.text = text
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})
-login required를 import 하여 사용한다.
from django.contrib.auth.decorators import login_required
원래의 코드는
if request.user.is_authenticated와 else 코드를 이용하여 작성하였는데 이를
decorator로 간단하게 변환한 것이다.
class는 함수와 다른 방식으로 decorator를 적용해야 한다.
@method_decorator(?, name=?) 방식으로 작성한다.
@method_decorator(login_required, name='get')
@method_decorator(login_required, name='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'
-위 방식대로 클래스에 적용한다.
-self.get_object() == self.request.user 데코레이터 추가
@method_decorator(login_required, name='get')
@method_decorator(login_required, name='post')
@method_decorator(account_ownership_required, name='get')
@method_decorator(account_ownership_required, name='post')
이를 리스트로 더 간결하게
has_ownership = [account_ownership_required, login_required]
# 생략
@method_decorator(has_ownership, name='get')
@method_decorator(has_ownership, name='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'
prfileapp 구현 시작 (0) | 2021.09.23 |
---|---|
profileapp 시작 그리고 ModelForm (0) | 2021.09.22 |
Authentication 인증 시스템 구축 (0) | 2021.09.22 |
DeleteView기반 회원탈퇴 구현 (0) | 2021.08.17 |
UpdateView를 이용한 비밀번호 변경 구현 (0) | 2021.08.17 |
댓글 영역