DeleteView

モデル

ListViewで使用した以下のmodelを使います。

View

DeleteBookViewクラスを作成しました。

# test_app/views.py
from django.views.generic import ListView
from django.views.generic.edit import CreateView, UpdateView, DeleteView

# Book を使うためにインポート
from .models import Book 
from .forms import BookForm

from django.urls import reverse, reverse_lazy

class BookListView(ListView):
    model = Book
    template_name = "test_app/book_list.html"
    context_object_name = "books"

class AddNewBookView(CreateView):
    model = Book
    template_name = "test_app/add_new_book.html"
    form_class = BookForm

    def get_success_url(self):
        # Book一覧に遷移する
        return reverse_lazy('book_list')
    
class UpdatebookView(UpdateView):
    model = Book
    template_name = "test_app/update_book.html"
    form_class = BookForm

    def get_success_url(self):
        # Book一覧に遷移する
        return reverse_lazy('book_list')
    
class DeleteBookView(DeleteView):
    model = Book
    template_name = "test_app/delete_book.html"

    def get_success_url(self):
        # Book一覧に遷移する
        return reverse_lazy('book_list')

Form

DeleteViewではFormの指定は必要ありません。

URL

DeleteBookView へのパスを追加しました。

from django.urls import path
from .views import *
  
urlpatterns = [
    # /にアクセスした時、BookListViewを呼び出す
    path("", BookListView.as_view(), name="book_list"),
    path("add_new_book", AddNewBookView.as_view(), name="add_book"),
    path("update_book/<int:pk>", UpdatebookView.as_view(), name="update_book"),
    path("delete_book/<int:pk>", DeleteBookView.as_view(), name="delete_book"),
]

テンプレート

test_app/delete_book.html を作成しました。

<h1>{{ book.title }}を編集</h1>

<form method="post">
  {% csrf_token %}
  <div>本のタイトル <br>{{ book.title }}</div><br>
  <div>本の説明 <br>{{ book.description }}</div><br>
  <div>著者 <br>{{ book.author }}</div><br>
  <div>記事の作成者 <br>{{ book.creator }}</div><br>

  <button type="submit">削除する</button>
</form>

また test_app/book_list.html にdelete_book へのURL追加しました。

<!-- test_app/templates/test_app/top_page.html -->
<!DOCTYPE html>
<html lang="ja">
    <head>
        <meta charset="UTF-8">
        <title>トップページ</title>
    </head>
    <body>
        <h1>ようこそ、トップページへ!</h1>

        {% for book in books %}
            <li>タイトル:{{ book.title }}</li>
            <li>本の説明:{{ book.description }}</li>
            <li>著者:{{ book.author }}</li>
            <li>記事の作成者:{{ book.creator }} <a href="{% url 'update_book' book.id %}">編集</a> <a href="{% url 'delete_book' book.id %}">削除</a></li>
            <br>

        {% endfor %}

        <a href="{% url 'add_book' %}">新しい本を追加</a>
    </body>
</html>

削除用のページが完成しました。「削除する」をクリックすると即時削除されるので、JavaScriptなどで削除確認の処理を入れると良いと思います。

コメント

タイトルとURLをコピーしました