第九章:建立編輯頁面

coffees/views.py

def index(request):
    ...


def show(request, pk):
    ...


def add(request):
    ...


def edit(request, pk):
    coffee = get_object_or_404(Coffee, pk=pk)
    form = CoffeeForm(request.POST or None, instance=coffee)
    if form.is_valid():
        form.save()
        messages.success(request, '更新成功')
        return redirect('coffees:index')
    return render(request, 'coffees/edit.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'),
]

templates/coffees/edit.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 ""