图书管理系统(无中间件,用装饰器的)-----未基于FORM组件

Posted 功不是凭梦想和希望,而是凭 努力和实践。

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了图书管理系统(无中间件,用装饰器的)-----未基于FORM组件相关的知识,希望对你有一定的参考价值。

目的:实现图书的增删改查

models.py

 

from django.db import models

# Create your models here.
class Book(models.Model):
    nid = models.AutoField(primary_key=True)  # 自增id(可以不写,默认会有自增id)
    title = models.CharField(max_length=32)
    publishDdata = models.DateField()  # 出版日期
    price = models.DecimalField(max_digits=5, decimal_places=2)  # 一共5位,保留两位小数

    #一个出版社有多本书,关联字段要写在多的一方
    # 不用命名为publish_id,因为django为我们自动就加上了_id
    publish = models.ForeignKey("Publish")  #foreignkey(表名)建立的一对多关系
    # publish是实例对象关联的出版社对象
    authorlist = models.ManyToManyField("Author")  #建立的多对多的关系
    def __str__(self):
        return self.title
class Publish(models.Model):
    #不写id的时候数据库会自动给你增加自增id
    name =models.CharField(max_length=32)
    addr = models.CharField(max_length=32)

    def __str__(self):
        return self.name
class Author(models.Model):
    name = models.CharField(max_length=32)
    age = models.IntegerField()
    def __str__(self):
        return self.name

class AuthorDeital(models.Model):
    tel = models.IntegerField()
    addr = models.CharField(max_length=32)
    author = models.OneToOneField("Author")  #建立的一对一的关系

class UserInfo(models.Model):
    username = models.CharField(max_length=32)
    password = models.CharField(max_length=32)

 

1、urls.py

 1 """周末作业aaa用图书管理系统django实现 URL Configuration
 2 
 3 The `urlpatterns` list routes URLs to views. For more information please see:
 4     https://docs.djangoproject.com/en/1.11/topics/http/urls/
 5 Examples:
 6 Function views
 7     1. Add an import:  from my_app import views
 8     2. Add a URL to urlpatterns:  url(r\'^$\', views.home, name=\'home\')
 9 Class-based views
10     1. Add an import:  from other_app.views import Home
11     2. Add a URL to urlpatterns:  url(r\'^$\', Home.as_view(), name=\'home\')
12 Including another URLconf
13     1. Import the include() function: from django.conf.urls import url, include
14     2. Add a URL to urlpatterns:  url(r\'^blog/\', include(\'blog.urls\'))
15 """
16 from django.conf.urls import url
17 from django.contrib import admin
18 from app01 import views
19 urlpatterns = [
20     url(r\'^admin/\', admin.site.urls),
21     url(r\'^del/(\\d+)$\', views.delbook),
22     url(r\'^add/$\', views.addbook),
23     # 方式一:通过路径
24     # url(r\'^edit/(\\d+)\', views.editbook),
25     # 方式二:通过数据
26     url(r\'^edit/$\', views.editbook),
27     url(r\'^chakan/$\', views.chakanbook),
28     url(r\'^login/$\', views.log_in),
29     url(r\'^index/$\', views.index),
30     url(r\'^reg/$\', views.reg),
31     url(r\'^log_out/$\', views.log_out),
32     url(r\'^set_pwd/$\', views.set_pwd),
33 ]
urls.py

2、views.py

  1 from django.shortcuts import render,redirect,HttpResponse
  2 from app01 import models
  3 # Create your views here.
  4 from django.contrib import auth   #auth模块
  5 from django.contrib.auth.models import User   #注册创建用户要用到
  6 from django.contrib.auth.decorators import login_required  #判断用户是否登录用到
  7 from django.core.paginator import Paginator,EmptyPage,PageNotAnInteger  #分页的时候要用到的
  8 @login_required  #查看用户是否登录
  9 def delbook(request,id):
 10     # 删除表中一行的图书信息
 11     # islogin = request.COOKIES.get("islogin", None)  # 获取cookies
 12     # if islogin:
 13     models.Book.objects.filter(nid=id).delete()
 14     return redirect("/chakan/")
 15 
 16 @login_required
 17 def addbook(request):
 18     # islogin = request.COOKIES.get("islogin", None)  # 获取cookies
 19     # if islogin:
 20     if request.method=="POST":
 21         # print(request.POST)
 22         title = request.POST.get("bookname")
 23         publishDdata = request.POST.get("data")
 24         author = request.POST.getlist("author")
 25         print("作者",author)
 26         price = request.POST.get("price")
 27         publish =int(request.POST.get("publish"))
 28         print("============",publish)
 29 
 30         # 吧作者添加进去
 31         book_obj = models.Book.objects.create(title=title, publishDdata=publishDdata,price=price, publish_id=publish)
 32         authors = models.Author.objects.filter(id__in=author)
 33         book_obj.authorlist.add(*authors)
 34         return redirect("/chakan/")
 35     else:
 36         pub_obj = models.Publish.objects.all()  #查出所有的出版社对象
 37         # print(pub_obj)
 38 
 39         authorlist=  models.Author.objects.all()
 40         print(authorlist)
 41         return render(request,"add.html",{"publist":pub_obj,"authorlist":authorlist})
 42 
 43 @login_required
 44 def editbook(request):
 45     # islogin = request.COOKIES.get("islogin", None)  # 获取cookies
 46     # if islogin:
 47     if request.method=="POST":
 48         # 如果是post请求
 49         # 先查出数据(怎么找到id呢?,隐藏一个input)
 50         # 修改数据方式一:
 51         id= request.POST.get("book_input_id")
 52         print("=====",id)
 53         title = request.POST.get("bookname")
 54         data = request.POST.get("data")
 55         price = request.POST.get("price")
 56         publish =int(request.POST.get("publish"))
 57         author = request.POST.getlist("author")
 58         # pubsh_id = models.Publish.objects.filter(name=publish)[0].id  #得到出版社的id
 59         models.Book.objects.filter(nid=id).update(title=title,publishDdata=data,price=price,publish_id=publish)
 60         #清除关系(清除你点击的哪一行)
 61         book_obj = models.Book.objects.filter(nid=id).first()
 62         book_obj.authorlist.clear()
 63         #然后再添加作者
 64         authors = models.Author.objects.filter(id__in=author)
 65         #绑定多对多关系
 66         book_obj.authorlist.add(*authors)
 67         return redirect("/chakan/")
 68     else:
 69         id = request.GET.get("book_id")
 70         print("id==========>",id)
 71         book_obj = models.Book.objects.filter(nid=id).first()
 72         auth_obj = models.Author.objects.all()
 73         print(book_obj)   #拿到对象:Book object
 74         publ_obj = models.Publish.objects.all()
 75 
 76         # 作者默认选定
 77         edit_book_authors = book_obj.authorlist.all().values_list("id")
 78         print(edit_book_authors)
 79         l = []
 80         for i in edit_book_authors:
 81             l.append(i[0])
 82         print(l)  #[3, 4]
 83         return render(request,"edit.html",{"book_obj":book_obj,"auth_obj":auth_obj,"publ_obj":publ_obj,"l":l})
 84 
 85 @login_required
 86 def chakanbook(request):
 87     \'\'\'
 88         批量导入
 89         Booklist = []
 90         for i in range(100):
 91 
 92              Booklist.append(models.Book(title="book" + str(i), price=20 + i * i))
 93 
 94         models.Book.objects.bulk_create(Booklist)
 95 
 96         :param request:
 97         :return:
 98         \'\'\'
 99     book_list = models.Book.objects.all()# book_list打印的是一个对象  先查看所有的书
100     paginator=Paginator(book_list,5)  #这里的book_list必须是一个集合对象,把所有的书分页,一页有五个
101     print(paginator.page_range)  #range(1, 4)
102     page_range = paginator.page_range
103     num = request.GET.get("page",2)#得到页数范围,默认有1页
104     print(num,type(num))
105     book_list = paginator.page(num) #显示第一页的内容
106     return render(request,"chakan.html",{"book_list":book_list,"page_range":page_range,"num":int(num)})
107 
108 
109 def log_in(request):
110     print(request.POST)
111     if request.method =="POST":
112         username = request.POST.get("username")
113         password = request.POST.get("password")
114         print(username,password)
115         user=auth.authenticate(username=username,password=password)#验证用户名和密码
116         if user:
117             #如果认证成功,就让登录,这个login里面包括了session操作和cookie
118             auth.login(request,user)
119             return redirect("/chakan/")
120         else:
121             s = "用户名和密码输入错误"
122             return render(request,"login.html",{"s":s})
123     return render(request,"login.html")
124 
125 @login_required
126 def index(request):
127     # print("cookies:------->",request.COOKIES)
128     # islogin = request.COOKIES.get("islogin",None)  #获取cookies
129     # print("=========",islogin)
130     # if islogin:
131     username = request.COOKIES.get("username")
132     return render(request,"chakan.html",{"username":username})
133 
134 
135 def reg(request):
136     if request.method=="POST":
137         username = request.POST.get("username")
138         password = request.POST.get("password")
139         #得到用户输入的用户名和密码创建一个新用户
140         User.objects.create_user(username=username,password=password)  #User是以个对象
141         s = "恭喜你注册成功,现在可以登录了"
142         return redirect("/login/")
143     return render(request,"reg.html")
144 
145 
146 
147 @login_required
148 def log_out(request):
149     auth.logout(request)
150     return redirect("/login/")
151 
152 @login_required
153 def set_pwd(request):
154     if request.method=="POST":
155         oldpassword = request.POST.get("oldpassword")
156         newpassword = request.POST.get("newpassword")
157         #得到当前登录的用户,判断旧密码是不是和当前的密码一样
158         username = request.user  #打印的是当前登录的用户名
159         user = User.objects.get(username=username)  #查看用户
160         ret = user.check_password(oldpassword)  #检查密码是否正确
161         if ret:
162             user.set_password(newpassword) #如果正确就给设置一个新密码
163             user.save()  #保存
164             return redirect("/login/")
165         else:
166             info = "输入密码有误"
167             return render(request,"set_pwd.html",{"info":info})
168     return render(request,"set_pwd.html")
views.py

3、template

 1 <!DOCTYPE html>
 2 <html lang="en">
 3 <head>
 4     <meta charset="UTF-8">
 5     <meta http-equiv="X-UA-Compatible" content="IE=edge">
 6     <meta name="viewport" content="width=device-width">
 7     <title>Title</title>
 8 </head>
 9 <body>
10 <h1>hello{{ username }}</h1>
11 </body>
12 </html>
index.html
  1 <!DOCTYPE html>
  2 <html lang="en">
  3 <head>
  4     <meta charset="UTF-8">
  5     <meta http-equiv="X-UA-Compatible" content="IE=edge">
  6     <meta name="viewport" content="width=device-width">
  7     <title>Title</title>
  8     <link rel="stylesheet" href="/static/bootstrap-3.3.7-dist/css/bootstrap.min.css">
  9     <!-- Bootstrap core CSS -->
 10     <link href="/static/Dashboard_files/bootstrap.min.css" rel="stylesheet">
 11 
 12     <!-- IE10 viewport hack for Surface/desktop Windows 8 bug -->
 13     <link href="/static/Dashboard_files/ie10-viewport-bug-workaround.css" rel="stylesheet">
 14 
 15     <!-- Custom styles for this template -->
 16     <link href="/static/Dashboard_files/dashboard.css" rel="stylesheet">
 17 
 18     <!-- Just for debugging purposes. Don\'t actually copy these 2 lines! -->
 19     <!--[if lt IE 9]>
 20     <script src="../../assets/js/ie8-responsive-file-warning.js"></script><![endif]-->
 21     <script src="/static/Dashboard_files/ie-emulation-modes-warning.js"></script>
 22 
 23     <!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
 24     <!--[if lt IE 9]>
 25 
 26     <![endif]
 27     <!--<link rel="stylesheet" href="bootstrap-3.3.7-dist/css/bootstrap.min.css">-->
 28         <style>
 29             {% block style %}
 30             .menu {
 31                 margin: 0 -20px;
 32                 border-bottom: 1px solid #336699;
 33             }
 34 
 35             .head {
 36                 padding: 15px;
 37             }
 38 
 39             .menu .nav-sidebar > li > a {
 40             padding-right: 40px;
 41             padding-left: 40px;
 42          }
 43 
 44             table {
 45                 margin-top: 50px;
 46                 margin-left: 40px;
 47             }
 48             .add{
 49                 margin-top: 20px;
 50          }
 51      {% endblock %}
 52     </style>
 53 
 54 </head>
 55 <body>
 56 <!--导航条-->
 57 <nav class="navbar navbar-inverse navbar-fixed-top">
 58     <div class="container-fluid">
 59         <div class="navbar-header">
 60             <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar"
 61                     aria-expanded="false" aria-controls="navbar">
 62                 <span class="sr-only">Toggle navigation</span>
 63                 <span class="icon-bar"></span>
 64                 <span class="icon-bar"></span>
 65                 <span class="icon-bar"></span>
 66             </button>
 67             <a class="navbar-brand" href="http://v3.bootcss.com/examples/dashboard/#左侧菜单.html">海燕图书管理系统</a>
 68         </div>
 69         <div id="navbar" class="navbar-collapse collapse">
 70             <ul class="nav navbar-nav navbar-right">
 71                 <li><a href="/log_out/">注销</a></li>
 72                 <li><a href="/set_pwd/">修改密码</a></li>
 73                 <li><a href="">设置</a></li>
 74                 <li><a href="">个人中心</a></li>
 75             </ul>
 76             <form class="navbar-form navbar-right">
 77                 <input type="text" class="form-control" placeholder="Search...">
 78             </form>
 79         </div>
 80     </div>
 81 </nav>
 82 <!--左侧菜单+-->
 83 <div class="container">
 84     <div class="left">
 85         <div class="以上是关于图书管理系统(无中间件,用装饰器的)-----未基于FORM组件的主要内容,如果未能解决你的问题,请参考以下文章

python-flask复习—— 装饰器的坑及解决办法flask中的路由/实例化配置/对象配置/蓝图/特殊装饰器(中间件重定义错误页面)

Python编程系列---Python中装饰器的几种形式及万能装饰器

在 Python 中充当装饰器和上下文管理器的函数?

装饰器

Javascript装饰器的妙用

装饰器的用法——用装饰器来记录函数被调用的次数