第十章:建立刪除頁面
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 = [
path('', views.index, name='index'),
path('<int:pk>/', views.show, name='show'),
path('add/', views.add, name='add'),
path('<int:pk>/edit/', views.edit, name='edit'),
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>
...