Django example -- book management operation

Example: Implement adding, deleting, and modifying books


Models.py file content:

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) #Define a one-to-many relationship and add the publish_id field to the book table
    author=models.ManyToManyField("Author") #Define a many-to-many relationship, which will specifically generate a relationship table between book and 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 file content:

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, ), #When editing, you need to pass in the id number of the edited book
    url(r'^del/(\d+)', views.delbook, ), #When deleting, you need to pass in the id number of the deleted book
]


views.py file content:

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)
        # Bind the one-to-many relationship between books and publishers
        obj=Book.objects.create(title=title,price=price,create_time=date,memo=memo,publish_id=publish_id)
        # Bind the many-to-many relationship between books and authors
        obj.author.add(*author_id_list)
        return redirect("/books/")
    else:
        publish_list=Publish.objects.all() #Get a collection of all publishing objects
        author_list=Author.objects.all() #Get a collection of all author objects
        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) #This sentence has the same effect as the above two sentences, both of which are rebinding to the author of the edited book
        return redirect("/books/") #After the modified data post, jump to the books page to display
    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 displays the page content of books:

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Book Information</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>serial number</th>
                              <th>Title</th>
                              <th>price</th>
                              <th>Published</th>
                              <th>Notes</th>
                              <th>Publisher</th>
                              <th>author</th>
                              <th>Action</th>
                               <th>Action</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>

list.png



addbook.html添加书籍的页面内容:

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Add Book</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>

add.png

editbook.htmlEdit the page content of the book:

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Edit Book</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 object is the same as the edited edit_book.publish object, indicating that it is selected#}
                                <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%} {# Determine whether the author is in the selected author 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>

edit.png




Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324646725&siteId=291194637