파이썬으로 장고(Django) 공략하기: 입문 강의를 정리한 내용입니다.

게시글 삭제

  • view 메소드를 추가하고 url을 연결한다.
# third/views.py
def delete(request):
    if 'id' in request.GET:
        item = get_object_or_404(Restaurant, pk=request.GET.get('id'))
        item.delete() # 삭제
    return HttpResponseRedirect('/third/list/')
# third/urls.py
from django.urls import path
from . import views

urlpatterns = [
    path('list/', views.list, name="list"),
    path('create/', views.create, name="restaurant-create"),
    path('update/', views.update, name="restaurant-update"),
    path('detail/', views.detail, name="restaurant-detail"),
    path('delete/', views.delete, name="restaurant-delete"),
]
  • 상세페이지에 삭제버튼을 추가하자.
<!-- third/templates/third/detail.html -->
{% extends 'third/base.html' %}
{% load static %}
{% block content %}
<div class="container">
    <div class="row">
        <div class="col-sm-12" style="margin-top:20px;">
            <h3>{{ item.name }}</h3>
            <p>{{ item.address }}</p>
            <p>
                <a href="{% url 'restaurant-delete' %}?id={{ item.id }}">
                    <button class="btn btn-danger">삭제하기</button>
                </a>
            </p>
        </div>
    </div>
</div>
{% endblock %}