django----图书管理

待完成

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",on_delete=models.CASCADE)  #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",on_delete=models.CASCADE)  #建立的一对一的关系

class UserInfo(models.Model):
    username = models.CharField(max_length=32)
    password = models.CharField(max_length=32)
models.py
from django.conf.urls import url
from django.contrib import admin
from web import views
urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^base/', views.base),
    url(r'^del/(d+)$', views.delbook),
    # url(r'^test',views.test),
    url(r'^add/$', views.addbook),
    # 方式一:通过路径
    url(r'^edit/(d+)', views.editbook),
    # 方式二:通过数据
    # url(r'^edit/$', views.editbook),
    url(r'^chakan/$', views.chakanbook),
    url(r'^login/$', views.log_in),
    url(r'^index/$', views.index),
    url(r'^reg/$', views.reg),
    url(r'^log_out/$', views.log_out),
    url(r'^set_pwd/$', views.set_pwd),
]
urls.py
from django.shortcuts import render,redirect,HttpResponse
from web import models
# Create your views here.
from django.contrib import auth   #auth模块
from django.contrib.auth.models import User   #注册创建用户要用到
from django.contrib.auth.decorators import login_required  #判断用户是否登录用到
from django.core.paginator import Paginator,EmptyPage,PageNotAnInteger  #分页的时候要用到的
@login_required  #查看用户是否登录
def delbook(request,id):
    # 删除表中一行的图书信息
    # islogin = request.COOKIES.get("islogin", None)  # 获取cookies
    # if islogin:
    models.Book.objects.filter(nid=id).delete()
    return redirect("/chakan/")



@login_required
def addbook(request):
    # islogin = request.COOKIES.get("islogin", None)  # 获取cookies
    # if islogin:
    if request.method=="POST":
        # print(request.POST)
        title = request.POST.get("bookname")
        publishDdata = request.POST.get("data")
        author = request.POST.getlist("author")
        print("作者",author)
        price = request.POST.get("price")
        publish =int(request.POST.get("publish"))
        print("============",publish)

        # 吧作者添加进去
        book_obj = models.Book.objects.create(title=title, publishDdata=publishDdata,price=price, publish_id=publish)
        authors = models.Author.objects.filter(id__in=author)
        book_obj.authorlist.add(*authors)
        return redirect("/chakan/")
    else:
        pub_obj = models.Publish.objects.all()  #查出所有的出版社对象
        # print(pub_obj)

        authorlist=  models.Author.objects.all()
        print(authorlist)
        return render(request,"add.html",{"publist":pub_obj,"authorlist":authorlist})


@login_required
def editbook(request,num):

    # islogin = request.COOKIES.get("islogin", None)  # 获取cookies
    # if islogin:
    if request.method=="POST":
        # 如果是post请求
        # 先查出数据(怎么找到id呢?,隐藏一个input)
        # 修改数据方式一:
        id= request.POST.get("book_input_id")
        print("=====",id)
        title = request.POST.get("bookname")
        data = request.POST.get("data")
        price = request.POST.get("price")
        publish =int(request.POST.get("publish"))
        author = request.POST.getlist("author")
        # pubsh_id = models.Publish.objects.filter(name=publish)[0].id  #得到出版社的id
        models.Book.objects.filter(nid=id).update(title=title,publishDdata=data,price=price,publish_id=publish)
        #清除关系(清除你点击的哪一行)
        book_obj = models.Book.objects.filter(nid=id).first()
        book_obj.authorlist.clear()
        #然后再添加作者
        authors = models.Author.objects.filter(id__in=author)
        #绑定多对多关系
        book_obj.authorlist.add(*authors)
        return redirect("/chakan/")
    else:
        # id = request.GET.get("book_id")

        # print("id==========>",id)
        # return HttpResponse("ok")
        id = num
        book_obj = models.Book.objects.filter(nid=id).first()
        auth_obj = models.Author.objects.all()
        #如果没有auth_obj 返回一个None  why
        print(book_obj)   #拿到对象:Book object
        publ_obj = models.Publish.objects.all()

        # 作者默认选定
        edit_book_authors = book_obj.authorlist.all().values_list("id")
        print(edit_book_authors)
        l = []
        for i in edit_book_authors:
            l.append(i[0])
        print(l)  #[3, 4]

        return render(request,"edit.html",{"book_obj":book_obj,"auth_obj":auth_obj,"publ_obj":publ_obj,"l":l})

@login_required
def chakanbook(request):
    '''
        批量导入
        Booklist = []
        for i in range(100):

             Booklist.append(models.Book(title="book" + str(i), price=20 + i * i))

        models.Book.objects.bulk_create(Booklist)

        :param request:
        :return:
        '''
    book_list = models.Book.objects.all()# book_list打印的是一个对象  先查看所有的书
    paginator=Paginator(book_list,5)  #这里的book_list必须是一个集合对象,把所有的书分页,一页有五个

    print(paginator.page_range)  #range(1, 4)
    page_range = paginator.page_range
    num = request.GET.get("page",1)#得到页数范围,默认有1页
    try:
        book_list = paginator.page(num) #显示第一页的内容
    except:
        book_list=None
    return render(request,"chakan.html",{"book_list":book_list,"page_range":page_range,"num":int(num)})


def log_in(request):
    print(request.POST)
    if request.method =="POST":
        username = request.POST.get("username")
        password = request.POST.get("password")
        print(username,password)
        user=auth.authenticate(username=username,password=password)#验证用户名和密码
        if user:
            #如果认证成功,就让登录,这个login里面包括了session操作和cookie
            auth.login(request,user)
            return redirect("/chakan/")
        else:
            s = "用户名和密码输入错误"
            return render(request,"login.html",{"s":s})
    return render(request,"login.html")

@login_required
def index(request):
    # print("cookies:------->",request.COOKIES)
    # islogin = request.COOKIES.get("islogin",None)  #获取cookies
    # print("=========",islogin)
    # if islogin:
    username = request.COOKIES.get("username")
    return render(request,"chakan.html",{"username":username})

#用于用户注册
def reg(request):
    if request.method=="POST":
        username = request.POST.get("username")
        password = request.POST.get("password")
        #得到用户输入的用户名和密码创建一个新用户
        User.objects.create_user(username=username,password=password)  #User是以个对象
        s = "恭喜你注册成功,现在可以登录了"
        return redirect("/login/")
    return render(request,"reg.html")



@login_required
def log_out(request):
    auth.logout(request)
    return redirect("/login/")

@login_required
def set_pwd(request):
    if request.method=="POST":
        oldpassword = request.POST.get("oldpassword")
        newpassword = request.POST.get("newpassword")
        #得到当前登录的用户,判断旧密码是不是和当前的密码一样
        username = request.user  #打印的是当前登录的用户名
        user = User.objects.get(username=username)  #查看用户
        ret = user.check_password(oldpassword)  #检查密码是否正确
        if ret:
            user.set_password(newpassword) #如果正确就给设置一个新密码
            user.save()  #保存
            return redirect("/login/")
        else:
            info = "输入密码有误"
            return render(request,"set_pwd.html",{"info":info})
    return render(request,"set_pwd.html")

def base(request):
    return render(request,"base.html")
views.py
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width">
    <title>Title</title>
    <link rel="stylesheet" href="/static/bootstrap.css">
        <style>
            {% block style %}
                /*
                */
            .menu {
                margin: 0 -20px;

                border-bottom: 1px solid #336699;
                 200px;
            }
            .container{
                margin-top: 50px;
            }
            .head {
                padding: 15px;
            }
            .menu .nav-sidebar > li > a {
            padding-right: 40px;
            padding-left: 40px;
             200px;
         }

            table {
                margin-top: 50px;
                margin-left: 40px;
            }
            .add{
                margin-top: 20px;
             }
            .head.bg-primary{
                 200px;
            }

            .left{
                /*
                background-color: rgba(255, 172, 73,0.2);
                */
                 20%;
                height: 600px;
                display: inline-block;
            }
            .right{
            /*
                background-color: #4cff48;
            */
                float: right;
                display: inline-block;
                 75%;
                height: 600px;

            }
     {% endblock %}
    </style>

</head>
<body>
<!--导航条-->

<nav class="navbar navbar-inverse navbar-fixed-top">
    <div class="container-fluid">
        <div class="navbar-header">
            <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar"
                    aria-expanded="false" aria-controls="navbar">
                <span class="sr-only">Toggle navigation</span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
            </button>
            <a class="navbar-brand" href="http://v3.bootcss.com/examples/dashboard/#左侧菜单.html">海燕图书管理系统</a>
        </div>
        <div id="navbar" class="navbar-collapse collapse">
            <ul class="nav navbar-nav navbar-right">
                <li><a href="/log_out/">注销</a></li>
                <li><a href="/set_pwd/">修改密码</a></li>
                <li><a href="">设置</a></li>
                <li><a href="">个人中心</a></li>
            </ul>
            <form class="navbar-form navbar-right">
                <input type="text" class="form-control" placeholder="Search...">
            </form>
        </div>
    </div>
</nav>



<div class="container">
    <!--左侧菜单+-->
    <div class="left">
                <div class="row">
            <div class="col-sm-3 col-md-2 sidebar">
                <div class="menu">
                    <div class="head bg-primary">图书管理操作</div>
                    <ul class="nav nav-sidebar">
                        <li><a href="/add/">》》添加图书</a></li>
                        <li><a href="editbook">》》修改图书</a></li>
                        <li><a href="/chakan/">》》查看图书</a></li>
                    </ul>
                </div>

                <div class="menu">
                    <div class="head  bg-primary">作者管理操作</div>
                    <ul class="nav nav-sidebar">
                        <li><a href="">》》添加作者</a></li>
                        <li><a href="">》》查看作者</a></li>
                        <li><a href="">》》编辑作者</a></li>
                    </ul>
                </div>

                <div class="menu">
                    <div class="head  bg-primary">出版社管理</div>
                    <ul class="nav nav-sidebar">
                        <li><a href="">》》添加出版社</a></li>
                        <li><a href="">》》查看出版社</a></li>
                        <li><a href="">》》编辑出版社</a></li>
                    </ul>
                </div>
            </div>
        </div>
    </div>
    <div class="right">
        {% block add%}

        {% endblock %}
    </div>
</div>




<script src="/static/jquery.min.js"></script>
<script src="/static/bootstrap.min.js"></script>
<script>
    //左侧菜单
    $(".head").on("click", function () {
        // 兄弟标签 紧挨着的ul标签 隐藏  addClass("hide")
        $(this).parent().siblings().children("ul").slideUp();
        // 把自己 紧挨着的ul标签显示  removeClass("hide")
//        $(this).next().removeClass("hide");
        $(this).next().slideToggle();
    });
</script>
</body>
</html>
base.html
{% extends "base.html" %}
{% block style %}
     {{ block.super }}
     .form-horizontal {
            margin-top: 100px;
        }
    .panel{
        margin-top:30px;
         700px;
        height: 500px;
        margin-left: 100px;
    }
{% endblock %}

{% block add %}
    <div class="panel panel-primary">
    <div class="panel-heading">添加书籍信息</div>
    <div class="panel-body">
        <form class="form-horizontal" action="/add/" method="post">
            {% csrf_token %}
            <div class="form-group">
                <label for="bookname" class="col-sm-2 control-label">书名:</label>
                <div class="col-sm-10">
                    <input type="text" name="bookname" id="bookname">
                </div>
            </div>
            <div class="form-group">
                <label for="data" class="col-sm-2 control-label">出版日期:</label>
                <div class="col-sm-10">
                    <input type="date" name="data" id="data">
                </div>
            </div>
            <div class="form-group">
                <label for="author" class="col-sm-2 control-label">作者:</label>
                <div class="col-sm-10">
                    <select name="author" id="author" multiple>
                        {% for author_obj in authorlist %}
                            <option value="{{ author_obj.id }}">{{ author_obj.name }}</option>
                        {% endfor %}
                    </select>
                </div>
            </div>
            <div class="form-group">
                <label for="price" class="col-sm-2 control-label">价格:</label>
                <div class="col-sm-10">
                    <input type="text" name="price" id="price">
                </div>
            </div>
            <div class="form-group">
                <label for="publish" class="col-sm-2 control-label">出版社:</label>
                <div class="col-sm-10">
                    <select name="publish" id="publish">
                        {% for pub_obj in publist %}
                            <option value="{{ pub_obj.id }}">{{ pub_obj.name }}</option>
                        {% endfor %}
                    </select>
                </div>
            </div>
            <div class="form-group">
                <div class="col-sm-10 col-md-offset-2">
                    <input type="submit">
                </div>
            </div>
        </form>
    </div>
</div>
{% endblock %}
add.html
{% extends "base.html" %}
{% block add %}
    <h1 class="pull-right" style="font-size: 30px">欢迎{{ request.user }}登录</h1>
        <div class="row">
            <div class="col-md-9 col-md-offset-2">
                <a href="/add/">
                    <button class="btn btn-primary add">添加图书</button>
                </a>
                <table class="table table-hover">
                    <thead>
                    <tr>
                        <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.publishDdata|date:'Y-m-d' }}</td>
                            <td>
                                {% for item in book.authorlist.all %}
                                    {{ item.name }}
                                {% endfor %}

                            </td>
                            <td>{{ book.price }}</td>
                            <td>{{ book.publish }}</td>
                            <td>
                                <a href="/del/{{ book.nid }}">
                                    <button class="btn btn-danger">删除</button>
                                </a>
                                                                <a href="/edit/{{ book.nid }}"><button class="btn btn-success">编辑</button></a>
                                <a href="/edit/?book_id={{ book.nid }}">
                                    <button class="btn btn-success">编辑</button>
                                </a>
                            </td>
                        </tr>
                    {% endfor %}
                    </tbody>
                </table>
            </div>
        </div>
    <nav aria-label="Page navigation" class="pull-right">
        <ul class="pagination">
            {% if book_list.has_previous %}
                <li><a href="/chakan?page={{ book_list.previous_page_number }}" aria-label="Previous">上一页</a></li>
            {% else %}
                <li class="disabled"><a href="" aria-label="Previous">上一页</a></li>
            {% endif %}

            {% for index in page_range %}
                {% if num == index%}
                    <li class="active"><a href="/chakan?page={{ index }}">{{ index }}</a></li>
                    {% else %}
                    <li><a href="/chakan?page={{ index }}">{{ index }}</a></li>
                {% endif %}

            {% endfor %}


            {% if book_list.has_next %}
                <li><a href="/chakan?page={{ book_list.next_page_number }}" aria-label="Previous">下一页</a></li>
            {% else %}
                <li class="disabled"><a href="" aria-label="Previous">下一页</a></li>
            {% endif %}
        </ul>
    </nav>
{% endblock %}
chakan.html
{% extends "base.html" %}
{% block style %}
     {{ block.super }}
      .form-horizontal {
            margin-top: 100px;
        }
        .panel{
            margin-top:30px;
             700px;
            height: 500px;
            margin-left:200px;
        }
{% endblock style %}

{% block add %}
<div class="panel panel-primary">
    <div class="panel-heading">修改图书信息</div>
    <div class="panel-body">
        <form class="form-horizontal" action="/edit/" method="post">
            {% csrf_token %}
            <div class="form-group">
                <div class="col-sm-10">
                    <input type="hidden" name="book_input_id" value="{{ book_obj.nid }}">
                </div>
            </div>
            <div class="form-group">
                <label for="bookname" class="col-sm-2 control-label">书名:</label>
                <div class="col-sm-10">
                    <input type="text" name="bookname" value="{{ book_obj.title }}">
                </div>
            </div>
            <div class="form-group">
                <label for="data" class="col-sm-2 control-label">出版日期:</label>
                <div class="col-sm-10">
                    <input type="date" name="data" value="{{ book_obj.publishDdata|date:"Y-m-d" }}">
                </div>
            </div>
            <div class="form-group">
                <label for="author" class="col-sm-2 control-label">作者:</label>
                <div class="col-sm-10">
                    <select name="author" id="author" multiple>
                        {% for auth in auth_obj %}
                            {% if auth.id in l %}
                               <option selected value="{{ auth.id }}">{{ auth.name }}</option>
                            {% else %}
                               <option value="{{ auth.id }}">{{ auth.name }}</option>
                            {% endif %}
                        {% endfor %}
                    </select>
                </div>
            </div>
            <div class="form-group">
                <label for="data" class="col-sm-2 control-label">价钱:</label>
                <div class="col-sm-10">
                    <input type="text" name="price" value="{{ book_obj.price }}">
                </div>
            </div>
         <div class="form-group">
                <label for="publish" class="col-sm-2 control-label">出版社:</label>
                <div class="col-sm-10">
                    <select name="publish" id="publish">
                        {% for publ in publ_obj %}
                            {% if publ.id == book_obj.publish.id %}
                                 <option value="{{ publ.id }}" selected>{{ publ.name }}</option>
                            {% endif %}
                            <option value="{{ publ.id }}">{{ publ.name }}</option>
                        {% endfor %}
                    </select>
                </div>
            </div>
             <div class="form-group">
                <div class="col-sm-10 col-md-offset-2">
                    <input type="submit">
                </div>
            </div>
        </form>
    </div>
</div>
{% endblock add %}
edit.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width">
    <title>Title</title>
</head>
<body>
<h1>hello{{ username }}</h1>
</body>
</html>
index.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width">
    <title>用户登录</title>
    <script src="/static/jquery.min.js"></script>
    <script src="/static/bootstrap.min.js"></script>
    <link rel="stylesheet" href="/static/bootstrap.css">

    <style>
        .c1{
            margin-top: 100px;
        }
        .btn{
             300px;
        }
        .c2{
            margin-left:80px;
        }
        .reg{
            text-decoration: none;
            color: white;
        }
    </style>
</head>
<body>
<div class="container">
    <div class="row">
        <div class="c1 col-md-5 col-md-offset-3">
            <form class="form-horizontal" action="/login/" method="post" novalidate>
                {% csrf_token %}
                <h3 style="color: red">{{ s }}</h3>
                <h3 style="text-align: center">请登录</h3>
                <div class="form-group">
                    <label for="username" class="col-sm-2 control-label">用户名</label>
                    <div class="col-sm-10">
                        <input type="email" class="form-control" id="username" placeholder="username" name="username">
                    </div>
                </div>
                <div class="form-group">
                    <label for="password" class="col-sm-2 control-label">密码</label>
                    <div class="col-sm-10">
                        <input type="password" class="form-control" name="password" id="password"
                               placeholder="Password">
                    </div>
                </div>
                <div class="form-group">
                    <div class="col-sm-offset-2 col-sm-10">
                        <button type="submit" class="btn btn-primary">登录</button>
                    </div>
                </div>
            </form>
            <a href="/reg/" class="reg"><button type="submit" class="btn btn-success c2">注册</button></a>
        </div>
    </div>
</div>

</body>
</html>
login.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width">
    <title>用户登录</title>
    <link rel="stylesheet" href="/static/bootstrap.css">
    <script src="/static/bootstrap.min.js"></script>
    <style>
        .c1{
            margin-top: 100px;
        }
        .c2{
             100px;
            margin-left: 80px;
        }
        .c3{
             100px;
            margin-left: 90px;
        }
    </style>
</head>
<body>
<div class="container">
    <div class="row">
        <div class="c1 col-md-5 col-md-offset-3">
            <form class="form-horizontal" action="/reg/" method="post" novalidate>
                {% csrf_token %}
                <h3 style="text-align: center">请填写下面信息注册</h3>
                <div class="form-group">
                    <label for="username" class="col-sm-2 control-label">用户名</label>
                    <div class="col-sm-10">
                        <input type="email" class="form-control" id="username" placeholder="username" name="username">
                    </div>
                </div>
                <div class="form-group">
                    <label for="password" class="col-sm-2 control-label">密码</label>
                    <div class="col-sm-10">
                        <input type="password" class="form-control" name="password" id="password"
                               placeholder="Password">
                    </div>
                </div>
                <input type="submit" class="c2">
                <input type="submit" class="c3" value="取消">
            </form>
        </div>
    </div>
</div>

</body>
</html>
reg.html
{% extends "base.html" %}
{% block style %}
    {{ block.super }}
    .form-horizontal {
    margin-top: 100px;
    }
    .panel{
    margin-top:30px;
     700px;
    height: 500px;
    margin-left: 200px;
    }
    .btn{
    150px;
    margin-left:200px;
    }

{% endblock %}

{% block add %}
    <div class="container">
        <div class="row">
            <div class="col-md-6 c1">
                <div class="panel panel-danger">
                    <div class="panel-heading">
                        <h3 class="panel-title">修改密码</h3>
                    </div>
                    <div class="panel-body">
                        <form class="form-horizontal" method="post" action="/set_pwd/">
                            {% csrf_token %}
                            <div class="form-group">
                                <label for="oldpassword" class="col-sm-2 control-label">旧密码</label>
                                <div class="col-sm-6">
                                    <input type="password" class="form-control" id="oldpassword"
                                           placeholder="Oldpassword"
                                           name="oldpassword">
                                </div>
                            </div>
                            <div class="form-group">
                                <label for="newpassword" class="col-sm-2 control-label">新密码</label>
                                <div class="col-sm-6">
                                    <input type="password" class="form-control" id="newpassword"
                                           placeholder="Newpassword"
                                           name="newpassword">
                                </div>
                            </div>
                           <button type="submit" class="btn btn-success">确定</button>
                        </form>

                        <h3>{{ info }}</h3>
                    </div>
                </div>
            </div>
        </div>
    </div>
{% endblock %}
set_pwd.html
原文地址:https://www.cnblogs.com/yanxiaoge/p/10613739.html