# commentapp\views.py
# ...
@method_decorator(comment_ownership_required, 'get')
@method_decorator(comment_ownership_required, 'post')
class CommentDeleteView(DeleteView):
model = Comment
context_object_name = 'target_comment'
template_name = 'commentapp\delete.html'
def get_success_url(self):
return reverse('articleapp:detail', kwargs={'pk': self.object.article.pk})
<!-- commentapp\delete.html -->
{% extends 'base.html' %}
{% load bootstrap4 %}
{% block content %}
<div style="text-align: center; max-width: 500px; margin: 4rem auto">
<div class="mb-4">
<h4>Delete Comment : {{ target_comment.content }}</h4>
</div>
<div>
<form action="{% url 'commentapp:delete' pk=target_comment.pk %}" method="post">
{% csrf_token %}
{% bootstrap_form form %}
<input type="submit" class="btn btn-danger rounded-pill col-6 mt-3">
</form>
</div>
</div>
{% endblock %}
# commentapp\decorator.py
def comment_ownership_required(func):
def decorated(request, *args, **kwargs):
comment = Comment.objects.get(pk=kwargs['pk'])
if not comment.writer == request.user:
return HttpResponseForbidden()
return func(request, *args, **kwargs)
return decorated
<!-- commentapp\detail.html -->
<div style="border: 1px solid; text-align: left; padding: 4%; margin: 1rem 0; border-radius: 1rem; border-color: #bbb">
<div>
<strong>
{% if comment.writer.profile.nickname %}
{{ comment.writer.profile.nickname }}
{% else %}
No nickname
{% endif %}
</strong>
<!--   : 띄어쓰기 -->
   
{{ comment.created_at }}
</div>
<div style="margin: 1rem 0;">
{{ comment.content }}
</div>
{% if comment.writer == user %}
<div style="text-align: right">
<a href="{% url 'commentapp:delete' pk=comment.pk %}" class="btn btn-danger rounded-pill">
Delete
</a>
</div>
{% endif %}
</div>
# commentapp\urls.py
app_name = 'commentapp'
urlpatterns = [
path('create/', CommentCreateView.as_view(), name='create'),
path('delete/<int:pk>', CommentDeleteView.as_view(), name='delete'),
]