상세페이지의 update,delete를 위한 소유권 확인
- 상세페이지의 pk 가져오기
urls.py
urlpatterns = [
path(
"update/<int:pk>",
ArticleUpdateView.as_view(),
name="update",
),
path(
"delete/<int:pk>",
ArticleDeleteView.as_view(),
name="delete",
),
]
- decorator 생성시 글 작성자와 로그인한 유저가 동일한지 확인
decorators.py
from django.http import HttpResponseForbidden
from articleapp.models import Article
def article_ownership_required(func):
def decorated(request, *args, **kwargs):
article = Article.objects.get(pk=kwargs["pk"])
if not article.writer == request.user:
return HttpResponseForbidden()
return func(request, *args, **kwargs)
return decorated
- view에서 실제로 적용하기
views.py
@method_decorator(article_ownership_required, "get")
@method_decorator(article_ownership_required, "post")
class ArticleUpdateView(UpdateView):
model = Article
form_class = ArticleCreationForm
context_object_name = "target_article"
template_name = "articleapp/update.html"
def get_success_url(self):
return reverse("articleapp:detail", kwargs={"pk": self.object.pk})
- 리스트형태로 decorator 가져오기 가능
views.py
# decorators.py에서 사용할 decorator를 가져와 리스트에 삽입
has_owership = [login_required, article_ownership_required]
@method_decorator(has_owership, "get")
@method_decorator(has_owership, "post")
class ArticleUpdateView(UpdateView):
model = Article
form_class = ArticleCreationForm
context_object_name = "target_article"
template_name = "articleapp/update.html"
def get_success_url(self):
return reverse("articleapp:detail", kwargs={"pk": self.object.pk})
728x90