Models数据表:
from django.db import models


class Books(models.Model):
    # 图书ID:默认自动创建,这里手动创建
    booksid = models.AutoField(primary_key=True, unique=True, null=False, max_length=11)
    # 图书种类:如果用默认值就必须得用max_length
    booksspecies = models.CharField(max_length=6, default='计算机')
    # 图书名称,null=False:不允许为空值,unique=True:不允许重复
    booksname = models.CharField(max_length=16, null=False, unique=True)
    # 图书几本
    booksnumber = models.IntegerField(null=False)
    # 图书国籍:中国,美国,英国
    bookscountry = models.CharField(max_length=4, null=False)
    # 图书是否入库:默认值没有入库
    booksstorage = models.BooleanField(default=False)
    # 图书价格
    booksmoney = models.CharField(max_length=10, null=False)
    # 添加图书时间:auto_now_add:第一次创建的时候自动设置当前日期,默认值:false
    bookstimes = models.DateTimeField(auto_now=True)
    #图书图片名称
    booksimg_name=models.CharField(max_length=50, null=False)
    # 图书图片:upload_to='%Y/%m/%d/icons'每张图片都有自己独立的按时间日期的文件夹,当天上传的图片都放在一个文件夹当中
    booksimg = models.FileField(null=True,upload_to='%Y/%m/%d/pic')

    class Meta:
        # 更改表名称为Books,如果不更改就是,App名_models类名。
        db_table = 'Books'


urls路由:


urlpatterns = [
    # django 2.0以下可以直接用url来进行正则表达式传参。2.0以上是直接使用path来进行传参,如果path没有满足传参类型,还可以用re_path()直接使用正则表达式来进行传参
    # 传递参数说明:
    # str- 匹配除路径分隔符之外的任何非空字符串'/'。如果转换器未包含在表达式中,则这是默认值。
    # int - 匹配零或任何正整数。返回一个int。
    # slug - 匹配由ASCII字母或数字组成的任何slug字符串,以及连字符和下划线字符。例如, building-your-1st-django-site。
    # uuid - 匹配格式化的UUID。要防止多个URL映射到同一页面,必须包含短划线并且字母必须为小写。例如,075194d3-6885-417e-a8a8-6c931e272f00。返回一个 UUID实例。
    # path- 匹配任何非空字符串,包括路径分隔符 '/'。这使您可以匹配完整的URL路径,而不仅仅是URL路径的一部分str。
    path('getbook/<int:booksid>/', views.get_book, name='get_book'),
    path('addbook/', views.add_book, name='add_book'),
    path('delbook/<int:booksid>/', views.del_book, name='del_book'),
    path('delallbook/', views.del_allbook, name='del_allbook'),
    path('updatebook/<int:booksid>/', views.update_book, name='update_book'),
    path('serchbook/<int:booksid>/', views.serch_book, name='serch_book'),
]


views视图:


import os

from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage
from django.shortcuts import render, redirect
from django.urls import reverse

from Book.models import Books


def get_book(request, booksid):
    course_list = Books.objects.all().order_by("-booksid")
    paginator = Paginator(course_list, 10)
    page = request.GET.get("page", booksid)
    currentPage = int(page)
    try:
        video_list = paginator.page(page)
    except PageNotAnInteger:
        video_list = paginator.page(1)
    except EmptyPage:
        video_list = paginator.page(paginator.num_pages)
    return render(request, 'allbooks.html', locals())


def serch_book(request, booksid):
    if request.method == "GET":
        name = request.GET.get("booksname")
        country = request.GET.get("bookscountry")
        money = request.GET.get("booksmoney")
        if not name != "" or money != "" or country != "":
            ob_list = Books.objects.all().order_by("-booksid")
        if name != "" or money != "" or country != "":
            ob_list = Books.objects.filter(booksname=name).filter(bookscountry=country).filter(
            booksmoney=money).order_by("-booksid")
        if name != "":
            ob_list = Books.objects.filter(booksname=name).order_by("-booksid")
        if money != "":
            ob_list = Books.objects.filter(booksmoney=money).order_by("-booksid")
        if country != "":
            ob_list = Books.objects.filter(bookscountry=country).order_by("-booksid")
        paginator = Paginator(ob_list, 10)
        page = request.GET.get("page", booksid)
        currentPage = int(page)
        try:
            video_list = paginator.page(page)
        except PageNotAnInteger:
            video_list = paginator.page(1)
        except EmptyPage:
            video_list = paginator.page(paginator.num_pages)
        return render(request, 'serchbooks.html', locals())


def add_book(request):
    if request.method == "GET":
        return render(request, 'booksadd.html')
    elif request.method == "POST":
        booksname = request.POST.get("booksname")
        booksnumber = request.POST.get("booksnumber")
        bookscountry = request.POST.get("bookscountry")
        booksstorage = request.POST.get("booksstorage")
        booksmoney = request.POST.get("booksmoney")
        money = format(float(booksmoney), '.2f')
        booksimg_name = request.POST.get("booksimg_name")
        booksimg = request.FILES.get("booksimg")
        # 如果图片名称和图片已与数据表的信息一致将返回添加页面
        lists = Books.objects.all()
        for i in lists:
            if booksimg_name == i.booksimg_name or booksimg == i.booksimg:
                return render(request, 'booksadd.html')
        max_upload_size = 5242880
        extenedname = booksimg_name[booksimg_name.rindex('.') + 1:]
        allowedname = ['jpg', 'png', 'pdf', 'txt', 'zip']
        if extenedname not in allowedname or (booksimg.size > max_upload_size):
            return render(request, 'booksadd.html')
        # 使用try...except的原因是注册的用户名有可能会一样,except Exception as ex:是捕获所有异常
        try:
            # 第一种保存数据写法:
            save = Books.objects.create(booksname=booksname, booksnumber=booksnumber, bookscountry=bookscountry, booksstorage=booksstorage, booksmoney=money, booksimg_name=booksimg_name, booksimg=booksimg)
            # 第二种保存数据写法:
            # st_save = Books()
            # st_save.booksname = booksname
            # st_save.booksnumber = booksnumber
            # st_save.bookscountry = bookscountry
            # st_save.booksstorage = booksstorage
            # st_save.booksmoney = money
            # st_save.booksimg_name = booksimg_name
            # st_save.booksimg = booksimg
            # st_save.save()
            return redirect(reverse("book:get_book",kwargs={'booksid':1}))
        except Exception as ex:
            return redirect(reverse("book:add_book"))


def update_book(request, booksid):
    if request.method == "GET":
        ob = Books.objects.get(pk=booksid)
        context = {'data': ob}
        return render(request, 'booksupdate.html', context)
    elif request.method == "POST":
        try:
            print(booksid)
            obs = Books.objects.get(pk=booksid)
            obs.booksname = request.POST['booksname']
            obs.booksnumber = request.POST['booksnumber']
            obs.bookscountry = request.POST['bookscountry']
            obs.booksstorage = request.POST['booksstorage']
            obs.booksmoney = format(float(request.POST['booksmoney']), '.2f')
            obs.booksimg_name = request.POST['booksimg_name']
            max_upload_size = 5242880
            extenedname = obs.booksimg_name[obs.booksimg_name.rindex('.') + 1:]
            allowedname = ['jpg', 'png', 'pdf', 'txt', 'zip']
            # 判断获取的文件后缀名是否在allowedname中
            if extenedname not in allowedname:
                ob = Books.objects.get(pk=booksid)
                context = {'data': ob}
                return render(request, 'booksupdate.html', context)
            # 如果获取表单文件==None,获取原有数据赋值给obs.booksimg。None是指字段里的值是空白不是null。
            if request.FILES.get("booksimg") == None:
                path_none = str(obs.booksimg)
                obs.booksimg = path_none
                obs.save()
                if request.FILES.get("booksimg") != "":
                    path_null = str(obs.booksimg)
                    obs.booksimg = path_null
                    obs.save()
            # 再如果获取表单文件的大小大于初始值max_upload_size:将进行返回所有数据重新上传文件
            elif request.FILES.get("booksimg").size > max_upload_size:
                ob = Books.objects.get(pk=booksid)
                context = {'data': ob}
                return render(request, 'booksupdate.html', context,)
            # 再如果获取表单文件!= obs.booksimg原有数据,则进行删除原有目录和文件名,并且把新获取到的目录和文件名进行更新
            elif request.FILES.get("booksimg") != obs.booksimg:
                path_booksimg = 'static/uploads/' + str(obs.booksimg)
                os.remove(path_booksimg)
                obs.booksimg = request.FILES.get("booksimg")
                obs.save()
            return redirect(reverse('book:get_book',kwargs={'booksid':1}))
        except Exception as ex:
            ob = Books.objects.get(pk=booksid)
            context = {'user': ob}
            return render(request, 'booksupdate.html', context)


def del_book(request, booksid):
    onedelete = Books.objects.get(pk=booksid)
    c = onedelete.booksid
    book = onedelete.booksimg
    path = 'static/uploads/' + str(book)
    onedelete.delete()
    os.remove(path)
    return redirect(reverse("book:get_book",kwargs={'booksid':1}))


def del_allbook(request):
    if request.method == "GET":
        return render(request, 'allbooks.html')
    elif request.method == "POST":
        ids = request.POST.getlist('booksid')
        for i in ids:
            deletesql = Books.objects.get(pk=i)
            book = deletesql.booksimg
            path = 'static/uploads/' + str(book)
            deletesql.delete()
            os.remove(path)
        return redirect(reverse('book:get_book',kwargs={'booksid':1}))