이번에는 DeleteView 에 대해서 알아보겠습니다.
PK 를 이용하여 해당 정보만 삭제하면 됩니다.
클래스 기반 뷰 하위에는 생성, 상세, 업데이트, 삭제, 리스트 등이 있다.
Model based Class base Views - Create, Detail, Update, Delete, List.
간단하게 설명하면, 모델에서 인스턴스 생성, 모델 인스턴스에 대한 DetailView 생성, 인스턴스 업데이트 및 삭제,
여러 인스턴스/디비에 있는 특정 모델의 모든 인스턴스 나열 이라고 할 수 있다.
views.py 에서 DeleteView 임포트, TeacherDeleteView 인스턴 생성 - class TeacherDeleteView(DeleteView):
from django.shortcuts import render
from django.urls import reverse_lazy, reverse
from django.views.generic import TemplateView, FormView, CreateView, ListView, DetailView, UpdateView, DeleteView
from classroom.forms import ContactForm
from classroom.models import TeacherModel
...
class TeacherDeleteView(DeleteView):
# Form --> Confirm Delete Button
# default template name:
# model_confirm_delete.html --> teachermodel_confirm_delete.html
model = TeacherModel
success_url = reverse_lazy('classroom:list_teacher')
urls.py
# domain.com/classroom
urlpatterns = [
# path('', views.home_view, name='home'), # path expects a function!
path('', views.HomeView.as_view(), name='home'), # 클래스를 가지고 경로에 대한 함수를 반환
path('thank_you/', views.ThankYouView.as_view(), name='thank_you'),
path('contact/', views.ContactFormView.as_view(), name='contact'),
path('create_teacher/', views.TeacherCreateView.as_view(), name='create_teacher'),
path('list_teacher/', views.TeacherListView.as_view(), name='list_teacher'),
path('detail_teacher/<int:pk>', views.TeacherDetailView.as_view(), name='detail_teacher'),
path('update_teacher/<int:pk>', views.TeacherUpdateView.as_view(), name='update_teacher'),
path('delete_teacher/<int:pk>', views.TeacherDeleteView.as_view(), name='delete_teacher'),
]
teachermodel_confirm_delete.html 생성
<body>
<h1>Are you sure you want to delete this teacher?</h1>
<h2>{{teachermodel}}</h2>
<form action="" method="post">
{% csrf_token %}
<input type="submit" value="Confirm Delete">
</form>
</body>
teachermodel_list.html 수정 - 삭제 버튼을 추가하여 Confirm 화면으로 이동시킨다.
<body>
<h1>List of Teachers (ListView)</h1>
<ul>
<!-- views 에서 context_object_name 을 설정하면 object_list->"설정한 변수명"으로 변경가능 -->
{% for teacher in teacher_list %}
<!-- <li>{{teacher.first_name}} {{teacher.last_name}}</li> -->
<li>
<a href="/classroom/detail_teacher/{{teacher.id}}">{{teacher.first_name}} {{teacher.last_name}}</a>
<button><a href="/classroom/update_teacher/{{teacher.id}}">Update Information</a></button>
<button><a href="/classroom/delete_teacher/{{teacher.id}}">Delete Information</a></button>
</li>
{% endfor %}
</ul>
</body>
실행 화면
'Python > Django' 카테고리의 다른 글
[Django] Linode 배포 - SSH (0) | 2022.12.20 |
---|---|
[Django] Linode 배포 - 가입 및 서버 생성 (0) | 2022.12.19 |
[Django] Class based View - UpdateView (0) | 2022.12.18 |
[Django] Class based View - DetailView (0) | 2022.12.17 |
[Django] Class based View - ListView (0) | 2022.12.17 |