本棚アプリケーションの作成【4-10 DeleteViewを作成してブラウザ上でデータを削除できるようにしよう】

データを削除するための画面を作成する

DeleteViewを作成します。これはデータを削除する際に使われます

実際にコードを書いていきます

bookproject/book/urls.py

from django.urls import path
from . import views

urlpatterns = [
    path('book/', views.ListBookView.as_view(), name='list-book'),
    path('book/<int:pk>/detail/', views.DetailBookView.as_view(),
name='detail-book'),
    path('book/create/', views.CreateBookView.as_view(), name='create-book'),
]

from django.urls import path
from . import views

urlpatterns = [
    path('book/', views.ListBookView.as_view(), name='list-book'),
    path('book/<int:pk>/detail/', views.DetailBookView.as_view(),
name='detail-book'),
    path('book/create/', views.CreateBookView.as_view(), name='create-book'),
    path('book/<int:pk>/delete/', views.DeleteBookView.as_view(),
name='delete-book')
]

に編集

bookproject/book/views.py

from django.shortcuts import render
from django.urls import reverse_lazy
from django.views.generic import ListView, DetailView, CreateView
from .models import Book

class ListBookView(ListView):
    template_name = 'book/book_list.html'
    model = Book

class DetailBookView(DetailView):
    template_name = 'book/book_detail.html'
    model = Book

class CreateBookView(CreateView):
    template_name = 'book/book_create.html'
    model = Book
    fields = ('title','text','category')
    success_url = reverse_lazy('list-book')

from django.shortcuts import render
from django.urls import reverse_lazy
from django.views.generic import ListView, DetailView, CreateView, DeleteView
from .models import Book

class ListBookView(ListView):
    template_name = 'book/book_list.html'
    model = Book

class DetailBookView(DetailView):
    template_name = 'book/book_detail.html'
    model = Book

class CreateBookView(CreateView):
    template_name = 'book/book_create.html'
    model = Book
    fields = ('title','text','category')
    success_url = reverse_lazy('list-book')

class DeleteBookView(DeleteView):
    template_name = 'book/book_confirm_delete.html'
    model = Book
    success_url = reverse_lazy('list-book')

に編集

book_confirm_delete.htmlファイルを作成していきます。

(venv) $ touch book/templates/book/book_confirm_delete.html

bookproject/book/templates/book/book_confirm_delete.html

{% extends 'base.html' %}

{% block title %}書籍排除{% endblock %}

{% block content %}
    <form method='POST'>{% csrf_token %}
        <button type="sybmit">{{ object.title }}を削除する</button>
    </form>
{% endblock %}

これでDeleteBookViewの完成です