第八章:建立新增頁面
from django import forms
from .models import Coffee
class CoffeeForm(forms.ModelForm):
class Meta:
fields = '__all__'
model = Coffee
coffees/views.py
from django.contrib import messages
from django.shortcuts import render, get_object_or_404, redirect
from .forms import CoffeeForm
from .models import Coffee
def index(request):
...
def show(request, pk):
...
def add(request):
form = CoffeeForm(request.POST or None)
if form.is_valid():
form.save()
messages.success(request, '新增成功')
return redirect('coffees:index')
return render(request, 'coffees/add.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'),
]
{% load bootstrap4 %}
<form action="" method="POST">
{% csrf_token %}
{% bootstrap_form form %}
<button type="submit" class="btn btn-outline-info float-right">送出</button>
</form>
templates/coffees/add.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/index.html
...
<div class="col">
<a href="{% url 'coffees:add' %}"
class="btn btn-outline-info float-right">
新增咖啡
</a>
<h2>咖啡列表</h2>
...
...
<div class="row">
<div class="col">
{% bootstrap_messages %}
{% block main %}{% endblock %}
</div>
</div>
...
成果