Django 之 練習3:書籍管理


代碼目錄結構

在這裏插入圖片描述


配置文件

settings.py

# 修改 admin 系統爲中文顯示
LANGUAGE_CODE = 'zh-hans'


邏輯代碼

urls.py

from django.contrib import admin
from django.urls import path, re_path
from app01 import views

urlpatterns = [
    path('admin/', admin.site.urls),

    path('book_list/', views.book_list),
    path('book_add/', views.BookAdd.as_view()),
    # 使用正則, 設定變量, 使用 CBV
    re_path('book_edit/(?P<id>\d+)/', views.BookEdit.as_view()),

]


views.py(app01)

from django.shortcuts import render, redirect, HttpResponse
from app01 import models
from django import views

# Create your views here.


def book_list(request):
    data = models.Book.objects.all()
    # locals()表示把所有變量都傳過去
    return render(request, "book_list.html", locals())


class BookAdd(views.View):

    def get(self, request):
        publish_data = models.Publisher.objects.all()
        author_data = models.Author.objects.all()
        return render(request, "book_add.html", locals())

    def post(self, request):
        title = request.POST.get("title")
        publish_date = request.POST.get("publish_date")
        publisher_id = request.POST.get("publisher")
        authors = request.POST.getlist("author")

        book_obj = models.Book.objects.create(
            title=title,
            publish_date=publish_date,
            publisher_id=publisher_id,
        )
        # 這兩個寫法都行, add 參數是多個元素, set 參數是一個列表
        book_obj.authors.add(*authors) # book_obj.authors.set(authors)
        return redirect("/book_list/")


class BookEdit(views.View):

    def get(self, request, id):
        book_obj = models.Book.objects.filter(id=id).first()
        publisher_list = models.Publisher.objects.all()
        author_list = models.Author.objects.all()
        return render(request, "book_edit.html", locals())

    def post(self, request, id):
        book_obj = models.Book.objects.filter(id=id).first()
        title = request.POST.get("title")
        publish_date = request.POST.get("publish_date")
        publisher_id = request.POST.get("publisher")
        authors = request.POST.getlist("author")
        
        book_obj.title = title
        book_obj.publisher_date = publish_date
        book_obj.publisher_id = publisher_id
        book_obj.save()
        
        book_obj.authors.set(authors)
        return redirect("/book_list/")


models.py

from django.db import models

# Create your models here.


class Publisher(models.Model):
	# 添加或者編輯時候的文字
    name = models.CharField(max_length=16, unique=True, verbose_name="出版社名稱")
    address = models.TextField(verbose_name="出版社地址")

	# 主頁展示的文字
    class Meta:
        verbose_name = "出版社"
        verbose_name_plural = verbose_name

    def __str__(self):
        return self.name


class Author(models.Model):
    name = models.CharField(max_length=16, verbose_name="姓名")
    gender = models.SmallIntegerField(
        choices=((0, "女"), (1, "男"), (2, "保密")),
        default=2,
        verbose_name="性別"
    )
    # null=True 聲明數據庫字段可以爲空, blank 聲明 admin 系統可以爲空
    age = models.IntegerField(verbose_name="年齡", null=True, blank=True)

    class Meta:
        verbose_name = "作者"
        verbose_name_plural = verbose_name

    def __str__(self):
        return self.name


class Book(models.Model):
    title = models.CharField(max_length=32, unique=True, verbose_name="書名")
    # 記錄創建時間
    publish_date = models.DateField(auto_now_add=True, verbose_name="出版時間")
    publisher = models.ForeignKey(to="Publisher", on_delete=models.CASCADE, verbose_name="出版社名稱")
    authors = models.ManyToManyField(to="Author", related_name="author", verbose_name="作者")

    class Meta:
        verbose_name = "書籍"
        verbose_name_plural = verbose_name

    def __str__(self):
        return self.title
        

template

publisher_list.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>書籍列表</title>
</head>
<body>

<h1>書籍列表</h1>

<a href="/book_add/">添加書籍</a>

<table border="1">
    <tbody>
    {% for book in data %}
        <tr>
        <td>{{ forloop.counter }}</td>
        <td>{{ book.id }}</td>
        <td>{{ book.title }}</td>
        <td>{{ book.publish_date }}</td>
        <td>{{ book.authors.all }}</td>
        <td>{{ book.publisher.name }}</td>
        <td><a href="/book_edit/{{ book.id }}/">編輯</a> <a href="/book_del/{{ book.id }}/">刪除</a></td>
        </tr>
    {% endfor %}
    </tbody>
</table>
</body>
</html>


publisher_add.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>添加書籍</title>
</head>
<body>

<h1>添加書籍</h1>

<form action="" method="post">
    {% csrf_token %}
    <p>
        書名
        <input type="text" name="title">
    </p>
    <p>
        出版日期
        <input type="date", name="publish_date">
    </p>
    <p>
        出版社
        <select name="publisher" id="">
            {% for datum in publish_data %}
                <option value="{{ datum.id }}">{{ datum.name }}</option>
            {% endfor %}
        </select>
    </p>
    <p>
        作者
        <select multiple name="author" id="">
            {% for datum in author_data %}
                <option value="{{ datum.id }}">{{ datum.name }}</option>
            {% endfor %}
        </select>
    </p>
    <input type="submit" value="添加">
</form>
</body>
</html>


publisher_edit.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>編輯書籍</title>
</head>
<body>

<h1>編輯書籍</h1>

<form action="" method="post">
    {% csrf_token %}
    <p>
        書名
        <input type="text" name="title" value="{{ book_obj.title }}">
    </p>
    <p>
        出版日期
        <input type="date" name="publish_date" value={{ book_obj.publish_date|date:"Y-m-d" }}>
    </p>
    <p>
        出版社
        <select name="publisher" id="">
            <!-- 循環出版社列表並展示, 如果書籍對象的出版社和當前循環的出版社相同, 則屬性修改爲選中 -->
            {% for datum in publisher_list %}
                {% if book_obj.publisher == datum %}
                    <option selected value="{{ datum.id }}">{{ datum.name }}</option>
                {% else %}
                    <option value="{{ datum.id }}">{{ datum.name }}</option>
                {% endif %}
            {% endfor %}
        </select>
    </p>
    <p>
        作者
        <select multiple name="author" id="">
            <!-- 循環作者列表並展示, 如果當前作者在書籍對象的作者列表中, 則屬性修改爲選中 -->
            {% for datum in author_list %}
                {% if datum in book_obj.authors.all %}
                    <option selected value="{{ datum.id }}">{{ datum.name }}</option>
                {% else %}
                    <option value="{{ datum.id }}">{{ datum.name }}</option>
                {% endif %}
            {% endfor %}
        </select>
    </p>
    <input type="submit" value="保存">
</form>
</body>
</html>


總結

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章