1. 程式人生 > >Django示例之--圖書管理操作

Django示例之--圖書管理操作

書籍管理系統 Django

示例:實現對圖書的添加,刪除,修改操作


models.py文件內容:

from django.db import models
# Create your models here.
class Book(models.Model):
    title=models.CharField(max_length=32)
    price=models.DecimalField(max_digits=6,decimal_places=2)
    create_time=models.DateField()
    memo=models.CharField(max_length=32,default="")
    publish=models.ForeignKey(to="Publish",default=1)       #定義一對多關系,會在book表添加publish_id字段
    author=models.ManyToManyField("Author")                 #定義多對多關系,會專門生成一張book和author的關系表
    def __str__(self):
        return self.title
class Publish(models.Model):
    name=models.CharField(max_length=32)
    email=models.CharField(max_length=32)
class Author(models.Model):
    name=models.CharField(max_length=32)
    def __str__(self):return self.name


urls.py文件內容:

from django.conf.urls import url
from django.contrib import admin
from app01 import views
urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^books/', views.books, ),
    url(r'^addbook/', views.addbook, ),
    url(r'^edit/(\d+)', views.editbook, ),        #編輯時,需要傳入編輯的書的id號
    url(r'^del/(\d+)', views.delbook, ),          #刪除時,需要傳入刪除的書的id號
]


views.py文件內容:

from django.shortcuts import render,HttpResponse,redirect
from .models import *
def books(reqeust):
    book_list=Book.objects.all()
    return render(reqeust,"books.html",locals())
def addbook(request):
    if request.method=="POST":
        title=request.POST.get("title")
        price=request.POST.get("price")
        date=request.POST.get("date")
        memo = request.POST.get("memo")
        publish_id=request.POST.get("publish_id")
        author_id_list=request.POST.getlist("author_id_list")
        print("author_id_list",author_id_list)
        # 綁定書籍與出版社的一對多的關系
        obj=Book.objects.create(title=title,price=price,create_time=date,memo=memo,publish_id=publish_id)
        # 綁定書籍與作者的多對多的關系
        obj.author.add(*author_id_list)
        return redirect("/books/")
    else:
        publish_list=Publish.objects.all()              #得到所有出版社對象的集合
        author_list=Author.objects.all()                #得到所有作者對象的集合
        return render(request,"addbook.html",locals())
def editbook(request,id):
    if request.method == "POST":
        title=request.POST.get("title")
        price=request.POST.get("price")
        date=request.POST.get("date")
        memo = request.POST.get("memo")
        publish_id=request.POST.get("publish_id")
        author_id_list=request.POST.getlist("author_id_list")
        Book.objects.filter(id=id).update(title=title,price=price,create_time=date,memo=memo,publish_id=publish_id)
        obj =Book.objects.filter(id=id).first()
        print(author_id_list)
        # obj.author.clear()
        # obj.author.add(*author_id_list)
        obj.author.set(author_id_list)               #這一句和上面兩句註釋的實現效果相同,都是對編輯的書的作者重新綁定
        return redirect("/books/")                   #修改後的數據post後,跳轉到books頁面展示
    edit_book=Book.objects.filter(id=id).first()
    publish_list = Publish.objects.all()
    author_list=Author.objects.all()                           #<QuerySet [<Author: song>, <Author: wang>, <Author: li>, <Author: zhang>]>
    author_obj=edit_book.author.all()                              #<QuerySet [<Author: zhang>, <Author: wang>]>
    author_selected_list=[author  for author in author_list if author in author_obj]  # [<Author: wang>, <Author: zhang>]
    return render(request,"editbook.html",locals())
def delbook(request,id):
    Book.objects.filter(id=id).delete()
    return redirect("/books/")

books.html展示書籍的頁面內容:

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>書籍信息</title>
    <style>
        .container{
            margin-top: 100px;
        }
    </style>
    <link rel="stylesheet" href="/static/bootstrap/css/bootstrap.css">
</head>
<body>
    <div>
        <div>
            <div class="col-md-6 col-md-offset-3">
                <a href="/addbook/"><button class="btn btn-primary">添加數據</button></a>
                <table class="table table-bordered table-striped">
                    <thead>
                         <tr>
                              <th>序號</th>
                              <th>書名</th>
                              <th>價格</th>
                              <th>出版時間</th>
                              <th>備註</th>
                              <th>出版社</th>
                              <th>作者</th>
                              <th>操作</th>
                               <th>操作</th>
                         </tr>
                    </thead>
                    <tbody>
                         {% for book in book_list %}
                         <tr>
                             <td>{{ forloop.counter }}</td>
                             <td>{{ book.title }}</td>
                             <td>{{ book.price }}</td>
                             <td>{{ book.create_time|date:"Y-m-d" }}</td>
                             <td>{{ book.memo }}</td>
                             <td>{{ book.publish.name }}</td>
                             <td>
                                 {% for author in book.author.all %}
                                 {{ author.name }}
                                     {% if not forloop.last %}            {#實現對最後一個作者的名字後面不加逗號#}
                                     ,
                                     {% endif %}
                                 {% endfor %}
                             </td>
                             <td>
                                <a href="/edit/{{ book.pk }}">編輯</a>
                             </td>
                            <td>
                                <a href="/edit/{{ book.pk }}">刪除</a>
                            </td>
                        </tr>
                         {% endfor %}
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</body>
</html>

技術分享圖片



addbook.html添加書籍的頁面內容:

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>添加書籍</title>
    <style>
        .container{
            margin-top: 100px;
        }
    </style>
    <link rel="stylesheet" href="/static/bootstrap/css/bootstrap.css">
</head>
<body>
    <div>
        <div>
            <div class="col-md-6 col-md-offset-3">
                <form action="/addbook/" method="post">
                    {% csrf_token %}
                    <p>書籍名稱 <input type="text" name="title"></p>
                    <p>書籍價格 <input type="text" name="price"></p>
                    <p>出版日期 <input type="date" name="date"></p>
                    <p>備註 <input type="text" name="memo"></p>
                    <p>出版社 <select name="publish_id" id="">
                        {% for publish in publish_list %}
                            <option value="{{ publish.pk }}">{{ publish.name }}</option>
                        {% endfor %}
                       </select>
                    </p>
                    <p>作者 <select name="author_id_list" id="" multiple>
                        {% for author in author_list %}
                            <option value="{{ author.pk }}">{{ author.name }}</option>
                        {% endfor %}
                       </select>
                    </p>
                    <input type="submit" class="btn btn-default">
                </form>
            </div>
        </div>
    </div>
</body>
</html>

技術分享圖片

editbook.html編輯書籍的頁面內容:

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>編輯書籍</title>
    <style>
        .container{
            margin-top: 100px;
        }
    </style>
    <link rel="stylesheet" href="/static/bootstrap/css/bootstrap.css">
</head>
<body>
    <div>
        <div>
            <div class="col-md-6 col-md-offset-3">
                <form action="/edit/{{ id }}" method="post">
                    {% csrf_token %}
                    <p>書籍名稱 <input type="text" name="title" value="{{ edit_book.title }}"></p>
                    <p>書籍價格 <input type="text" name="price" value="{{ edit_book.price }}"></p>
                    <p>出版日期 <input type="date" name="date" value="{{ edit_book.create_time| date:'Y-m-d' }}"></p>
                    <p>備註 <input type="text" name="memo" value="{{ edit_book.memo }}"> </p>
                    <p>出版社 <select name="publish_id" id="">
                        {% for publish in publish_list %}
                            {% if publish == edit_book.publish %}              {#publish對象和編輯的edit_book.publish對象一樣,表示被選中#}
                                <option selected  value="{{ publish.pk }}">{{ publish.name }}</option>
                             {% else%}
                                <option value="{{ publish.pk }}">{{ publish.name }}</option>
                            {% endif %}
                        {% endfor %}
                       </select>
                    </p>
                     <p>作者 <select type="checkbox" name="author_id_list" id="" multiple>
                        {% for author in author_list%}
                            {% if author in author_selected_list%}              {# 判斷作者是否在被選中的作者列表裏#}
                                    <option  value="{{ author.pk }}" selected="selected">{{ author.name }}</option>
                             {% else %}
                                    <option  value="{{ author.pk }}">{{ author.name }}</option>
                           {% endif %}
                        {% endfor %}
                       </select>
                    </p>
                    <input type="submit" class="btn btn-default">
                </form>
            </div>
        </div>
    </div>
</body>
</html>

技術分享圖片




Django示例之--圖書管理操作