(Django 기초) Commentapp - Delete

Posted by : at

Category : Django



# 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>
        <!-- &nbsp : 띄어쓰기 -->
        &nbsp&nbsp&nbsp
        {{ 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'),
]


About Taehyung Kim

안녕하세요? 8년차 현업 C++ 개발자 김태형이라고 합니다. 😁 C/C++을 사랑하며 다양한 사람과의 협업을 즐깁니다. ☕ 꾸준한 자기개발을 미덕이라 생각하며 노력중이며, 제가 얻은 지식을 홈페이지에 정리 중입니다. 좀 더 상세한 제 이력서 혹은 Private 프로젝트 접근 권한을 원하신다면 메일주세요. 😎

Star
Useful Links