第十章:建立刪除頁面

utils/forms.py

from django import forms


class DeleteConfirmForm(forms.Form):
    check = forms.BooleanField(label='你確定要刪除嗎?')

coffees/views.py

from utils.forms import DeleteConfirmForm
from .forms import CoffeeForm


def index(request):
    ...


def show(request, pk):
    ...


def add(request):
    ...


def edit(request, pk):
    ...


def delete(request, pk):
    coffee = get_object_or_404(Coffee, pk=pk)
    form = DeleteConfirmForm(request.POST or None)
    if form.is_valid() and form.cleaned_data['check']:
        coffee.delete()
        messages.success(request, '刪除成功')
        return redirect('coffees:index')
    return render(request, 'coffees/delete.html', {'form': form})

coffees/urls.py

from django.urls import path

from . import views

app_name = 'coffees'
urlpatterns = [
    # ex: /coffees/
    path('', views.index, name='index'),
    # ex: /coffees/1/
    path('<int:pk>/', views.show, name='show'),
    # ex: /coffees/add/
    path('add/', views.add, name='add'),
    # ex: /coffees/1/edit/
    path('<int:pk>/edit/', views.edit, name='edit'),
    # ex: /coffees/1/delete/
    path('<int:pk>/delete/', views.delete, name='delete'),
]

templates/coffees/delete.html

{% extends 'layout.html' %}

{% block main %}
<div class="row">
    <div class="col col-sm-10 offset-sm-1 col-md-8 offset-md-2 col-lg-6 offset-lg-3">
        <h2>刪除咖啡</h2>
        <hr>
        {% include 'share/_form.html' %}
    </div>
</div>
{% endblock %}

templates/coffees/show.html

...
{% block main %}
<!-- 加上導向刪除頁面的按鈕 -->
<a href="{% url 'coffees:edit' coffee.id %}"
   class="btn btn-info float-right mr-2">
    編輯
</a>
...

results matching ""

    No results matching ""