图书管理系统

数据库配置相关代码

数据库配置

/settings.py

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'app01.apps.App01Config',
]

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'bookmanager2',
        'HOST': '127.0.0.1',
        'PORT': 3306,
        'USER': 'root',
        'PASSWORD': '123',
    }
}

STATIC_URL = '/static/'

# 静态文件的实际存放目录
STATICFILES_DIRS = [
    os.path.join(BASE_DIR, 'static'),
]

/bookmanager/__init__.py

import pymysql

pymysql.install_as_MySQLdb()

/app01/models.py

from django.db import models

# Create your models here.


class User(models.Model):
    id = models.AutoField(primary_key=True)   # -> 创建一个自增的ID列作为主键
    email = models.CharField(max_length=24)  # -> varchar(32)
    pwd = models.CharField(max_length=16)  # -> varchar(32)

    def __str__(self):
        return self.email


# 出版社表
class Press(models.Model):
    id = models.AutoField(primary_key=True)  # id主键
    name = models.CharField(max_length=32)  # 出版社名称

    def __str__(self):
        return '<这是一个出版社对象,它的名字是:{}>'.format(self.name)


# 书
class Book(models.Model):
    id = models.AutoField(primary_key=True)  # 自增id主键
    title = models.CharField(max_length=30)  # 书名
    price = models.IntegerField(null=True)
    # Django 1.11 默认就是级联删除, Django 2.0之后必须指定on_delete
    # to=关联的表名
    press = models.ForeignKey(to='Press', on_delete=models.CASCADE)

# 作者
class Author(models.Model):
    id = models.AutoField(primary_key=True)  # 自增id主键
    name = models.CharField(max_length=32)  # 作者名字
    books = models.ManyToManyField(to='Book')  # 只是ORM层面建立的一个多对多关系,不是作者表的一个字段

    def __str__(self):
        return self.name

前端页面之母版

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta http-equiv="content-type" content="text/html; charset=UTF-8">
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <!-- 上述3个meta标签*必须*放在最前面,任何其他内容都*必须*跟随其后! -->
    <meta name="description" content="">
    <meta name="author" content="">
    <link rel="icon" href="https://v3.bootcss.com/favicon.ico">
    <title>Dashboard Template for Bootstrap</title>
    <!-- Bootstrap core CSS -->
    <link href="/static/bootstrap-3.3.7/css/bootstrap.css" rel="stylesheet">
    <!-- 当前页面用到的自定义样式 -->
    <link href="/static/dashboard.css" rel="stylesheet">
</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="#">Project name</a>
        </div>
        <div id="navbar" class="navbar-collapse collapse">
            <ul class="nav navbar-nav navbar-right">
                <li><a href="#">Dashboard</a></li>
                <li><a href="#">Settings</a></li>
                <li><a href="#">Profile</a></li>
                <li><a href="#">Help</a></li>
            </ul>
            <form class="navbar-form navbar-right">
                <input class="form-control" placeholder="Search..." type="text">
            </form>
        </div>
    </div>
</nav>

<div class="container-fluid">
    <div class="row">
        <div class="col-sm-3 col-md-2 sidebar">
            <ul class="nav nav-sidebar">
                <li class="{% block press %} {% endblock %}"><a href="/press_list/">出版社列表</a></li>
                <li class="{% block book %} {% endblock %}"><a href="/book_list/">书籍列表</a></li>
                <li class="{% block author %} {% endblock %}"><a href="/author_list/">作者列表</a></li>
            </ul>
        </div>
        <div class="col-sm-8 col-sm-offset-2 col-md-8 col-md-offset-2 main">
            {% block content %}

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

<!-- Bootstrap core JavaScript
================================================== -->
<!-- Placed at the end of the document so the pages load faster -->
<script src="/static/jquery-3.3.1.js"></script>
<script src="/static/bootstrap-3.3.7/js/bootstrap.js"></script>
</body>
</html>

图书管理系统之出版社的增删改查


表结构设计

出版社
id  name 

作者
id  name  

书
id  title 出版社_id

作者_书_关系表
id 书_id 作者_id

ORM版增删改查

类名.objects.all()		    	  --> 拿到所有的数据(列表)
类名.objects.filter()              --> 拿到符合条件的数据(列表)
类名.objects.get()                 --> 有且只能有一个返回结果(对象)
类名.objects.create(name='')       --> 创建一个对象,返回的就是刚创建的对象
类名.objects.filter(id=).delete()  --> 删除
				
obj = 类名.objects.get(id='')
obj.name = '新值'                  --> 修改对象的属性(修改数据行某个字段的值)
obj.save()                         --> 把修改同步到数据库
	

代码实现


后端业务逻辑

/bookmanager/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'^press_list/', views.press_list),
    url(r'^add_press/', views.add_press),
    url(r'^delete_press/', views.delete_press),
    url(r'^edit_press/', views.edit_press),
]

/app01/views.py

def press_list(request):
    press_obj = Press.objects.all().order_by('id')
    return render(request, 'list/press_list.html', locals())

def add_press(request):
    if request.method == 'POST':
        name = request.POST.get('name')
        Press.objects.create(name=name)
        return redirect('/press_list/')
    return render(request, 'add/add_press2.html')


def  delete_press(request):
    delete_id = request.GET.get('id')
    Press.objects.filter(id=delete_id).delete()

    return redirect('/press_list/')


def edit_press(request):
    id = request.GET.get('id')
    press_obj = Press.objects.get(id=id)

    if request.method == 'POST':
        new_name = request.POST.get('name')
        press_obj.name = new_name
        press_obj.save()
        return redirect('/press_list/')

    return render(request, 'edit/edit_press2.html', {'name': press_obj.name, 'edit_id': press_obj.id})

前端页面展示


/templates/list/press_list.html

{% extends 'list/base.html' %}
{% block press %}
active
{% endblock %}
{% block content %}
 <h1 class="page-header">出版社列表</h1>

            <!--面板 开始-->
            <div class="panel panel-default">
                <div class="panel-heading">出版社列表</div>
                <div class="panel-body">
                    <!--表格上面的那一行-->
                    <div class="row">
                        <div class="col-md-4">
                            <div class="input-group">
                                <input type="text" class="form-control" placeholder="Search for...">
                                <span class="input-group-btn">
                      <button class="btn btn-default" type="button">Go!</button>
                    </span>
                            </div><!-- /input-group -->
                        </div><!-- /.col-lg-6 -->
                        <div class="col-md-1 pull-right">
                            <a class="btn btn-success pull-right" href="/add_press/">添加</a>
                        </div>
                    </div>
                    <!--表格上面那一行 结束-->
                    <!--表格 开始-->
                    <div class="table-box">
                        <table class="table table-bordered table-striped">
                            <thead>
                            <tr>
                                <th class="text-center">序号</th>
                                <th class="text-center">出版社id</th>
                                <th class="text-center">出版社名字</th>
                                <th class="text-center">操作</th>
                            </tr>
                            </thead>
                            <tbody>
                            {% for i in press_obj %}
                                <tr class="text-center">
                                    <td>{{ forloop.counter }}</td>
                                    <td>{{ i.id }}</td>
                                    <td>{{ i.name }}</td>
                                    <td>
                                        <a class="btn btn-danger btn-sm" href="/delete_press/?id={{ i.id }}">删除</a>
                                        <a class="btn btn-info btn-sm"href="/edit_press/?id={{ i.id }}">编辑</a>
                                    </td>
                                </tr>
                            {% endfor %}
                            </tbody>
                        </table>
                    </div>
                    <!--表格 结束-->
                    <!--分页开始-->
                    <div>
                        <nav aria-label="Page navigation" class="pull-right">
                            <ul class="pagination">
                                <li>
                                    <a href="#" aria-label="Previous">
                                        <span aria-hidden="true">&laquo;</span>
                                    </a>
                                </li>
                                <li><a href="#">1</a></li>
                                <li><a href="#">2</a></li>
                                <li><a href="#">3</a></li>
                                <li><a href="#">4</a></li>
                                <li><a href="#">5</a></li>
                                <li>
                                    <a href="#" aria-label="Next">
                                        <span aria-hidden="true">&raquo;</span>
                                    </a>
                                </li>
                            </ul>
                        </nav>
                    </div>
                    <!--分页结束-->
                </div>
            </div>
            <!--面板 结束-->

{% endblock %}

/templates/add/add_press.html

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta http-equiv="content-Type" charset="UTF-8">
    <meta http-equiv="x-ua-compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="/static/bootstrap-3.3.7/css/bootstrap.css">
    <title>添加出版社</title>
</head>
<body>

<div class="container">
    <div class="row">
        <div class="col-md-6 col-md-offset-3">
            <div class="page-header">
                <h1>添加出版社</h1>
            </div>
            <form class="form-horizontal" action="/add_press/" method="post">
                {% csrf_token %}
                <div class="form-group">
                    <label for="press_name" class="col-sm-3 control-label">出版社名称</label>
                    <div class="col-sm-9">
                        <input type="text" class="form-control" id="press_name" name="name" placeholder="出版社名称">
                    </div>
                </div>

                <div class="form-group">
                    <div class="col-sm-offset-3 col-sm-9">
                        <button type="submit" class="btn btn-default">添加</button>
                    </div>
                </div>
            </form>
        </div>
    </div>
</div>


</body>
</html>

/templates/edit/edit_press.html

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta http-equiv="content-Type" charset="UTF-8">
    <meta http-equiv="x-ua-compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="/static/bootstrap-3.3.7/css/bootstrap.css">
    <title>添加出版社</title>
</head>
<body>

<div class="container">
    <div class="row">
        <div class="col-md-6 col-md-offset-3">
            <div class="page-header">
                <h1>编辑出版社</h1>
            </div>
            <form class="form-horizontal" action="/edit_press/?id={{ edit_id }}" method="post">
                {% csrf_token %}
                <div class="form-group">
                    <label for="press_name" class="col-sm-3 control-label">出版社名称</label>
                    <div class="col-sm-9">
                        <input type="text" class="form-control" id="press_name" name="name" value="{{ name }}">
                    </div>
                </div>

                <div class="form-group">
                    <div class="col-sm-offset-3 col-sm-9">
                        <button type="submit" class="btn btn-default">确认修改</button>
                    </div>
                </div>
            </form>
        </div>
    </div>
</div>


</body>
</html>

图书管理系统之书籍的增删改查


书籍表结构设计

		1. id  title 出版社_id
		2. SQL
			create table book (
				id int primary key auto_increment,
				title varchar(30) not null,
				press_id int not null,
				constraint fk_press foreign key(press_id) references press(id) 
				on delete cascade
				on update cascade
			)
		3. ORM外键
			press = models.ForignKey(to='Press', on_delete=models.CASCADE)

书籍的增删改查

1. 查询
			1. book_obj.press              --> ORM层面封装的,返回的是和我这本书关联的出版社对象
			2. book_obj.press_id           --> 数据库中真正存在的字段,保存的是和我关联的出版社id值

2. 增加
			1. 用select标签把已经存在的出版社在页面上展示出来
			   让用户去选择
			   使用的是:模板语言的for循环
      
<select name="press_id" class="form-control">
                        {% for press in press_data %}
                            <option value="{{ press.id }}">{{ press.name }}</option>
                        {% endfor %}
                    </select>

3. 删除
			类名.objects.filter(id=).delete()
			补充一个3秒钟之后跳转到指定页面的操作
				1. location.href
				2. setTimeout()
				3. setinterval()		

4. 编辑 
      obj = 类名.objects.get(id='')
      obj.name = '新值'       --> 修改对象的属性(修改数据行某个字段的值)
      obj.save()              --> 把修改同步到数据库
      
			用select标签展示默认的出版社
      <select name="press_id" class="form-control">
                        {% for press in press_list %}
                            <option value="{{ press.id }}">{{ press.name }}</option>
                        {% endfor %}
                    </select>

代码实现



后端业务逻辑

/bookmanager/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'^press_list/', views.press_list),
    url(r'^add_press/', views.add_press),
    url(r'^delete_press/', views.delete_press),
    url(r'^edit_press/', views.edit_press),


    url(r'^book_list/', views.book_list),
    url(r'^add_book/', views.add_book),
    url(r'^delete_book/', views.delete_book),
    url(r'^edit_book/', views.edit_book),

]

/app01/views.py

from django.shortcuts import render, redirect

# Create your views here.

from .models import Press, Book

def book_list(request):
    book_obj = Book.objects.all()

    return render(request, 'list/book_list.html', locals())

def add_book(request):
    press_data = Press.objects.all()
    if request.method == 'POST':
        book_name = request.POST.get('book_name')
        press_id = request.POST.get('press_id')
        Book.objects.create(title=book_name, press_id=press_id)
        return redirect('/book_list/')

    return render(request, 'add/add_book.html', locals())


def delete_book(request):
    delete_id = request.GET.get('id')
    Book.objects.filter(id=delete_id).delete()
    return render(request, 'delete/delete_success.html')


def edit_book(request):
    edit_id = request.GET.get('id')
    book_obj = Book.objects.get(id=edit_id)
    press_data = Press.objects.all()
    if request.method == 'POST':
        new_name = request.POST.get('book_name')
        press_id = request.POST.get('press_id')
        book_obj.title = new_name
        book_obj.press_id = press_id
        book_obj.save()
        return redirect('/book_list/')

    return render(request, 'edit/edit_book.html', {'book_name': book_obj.title, 'edit_id': edit_id, 'press_list': press_data})

前端页面展示


/templates/list/book_list.html

{% extends 'list/base.html' %}
{% block book %}
active
{% endblock %}
{% block content %}
 <h1 class="page-header">书籍列表</h1>

            <!--面板 开始-->
            <div class="panel panel-default">
                <div class="panel-heading">书籍列表</div>
                <div class="panel-body">
                    <!--表格上面的那一行-->
                    <div class="row">
                        <div class="col-md-4">
                            <div class="input-group">
                                <input type="text" class="form-control" placeholder="Search for...">
                                <span class="input-group-btn">
                      <button class="btn btn-default" type="button">Go!</button>
                    </span>
                            </div><!-- /input-group -->
                        </div><!-- /.col-lg-6 -->
                        <div class="col-md-1 pull-right">
                            <a class="btn btn-success pull-right" href="/add_book/">添加</a>
                        </div>
                    </div>
                    <!--表格上面那一行 结束-->
                    <!--表格 开始-->
                    <div class="table-box">
                        <table class="table table-bordered table-striped">
                            <thead>
                            <tr>
                                <th class="text-center">序号</th>
                                <th class="text-center">书籍id</th>
                                <th class="text-center">书籍名称</th>
                                <th class="text-center">出版社名称</th>
                                <th class="text-center">操作</th>
                            </tr>
                            </thead>
                            <tbody>
                            {% for i in book_obj %}
                                <tr class="text-center">
                                    <td>{{ forloop.counter }}</td>
                                    <td>{{ i.id }}</td>
                                    <td>{{ i.title }}</td>
                                    <td>{{ i.press.name }}</td>
                                    <td>
                                        <a class="btn btn-danger btn-sm" href="/delete_book/?id={{ i.id }}">删除</a>
                                        <a class="btn btn-info btn-sm"href="/edit_book/?id={{ i.id }}">编辑</a>
                                    </td>
                                </tr>
                            {% endfor %}
                            </tbody>
                        </table>
                    </div>
                    <!--表格 结束-->
                    <!--分页开始-->
                    <div>
                        <nav aria-label="Page navigation" class="pull-right">
                            <ul class="pagination">
                                <li>
                                    <a href="#" aria-label="Previous">
                                        <span aria-hidden="true">&laquo;</span>
                                    </a>
                                </li>
                                <li><a href="#">1</a></li>
                                <li><a href="#">2</a></li>
                                <li><a href="#">3</a></li>
                                <li><a href="#">4</a></li>
                                <li><a href="#">5</a></li>
                                <li>
                                    <a href="#" aria-label="Next">
                                        <span aria-hidden="true">&raquo;</span>
                                    </a>
                                </li>
                            </ul>
                        </nav>
                    </div>
                    <!--分页结束-->
                </div>
            </div>
            <!--面板 结束-->
{% endblock %}

/templates/add/add_book.html

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta http-equiv="content-Type" charset="UTF-8">
    <meta http-equiv="x-ua-compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="/static/bootstrap-3.3.7/css/bootstrap.css">
    <title>添加书籍</title>
</head>
<body>

<div class="container">
    <div class="row">
        <div class="col-md-6 col-md-offset-3">
            <div class="page-header">
                <h1>添加书籍</h1>
            </div>
            <form class="form-horizontal" action="/add_book/" method="post">
            {% csrf_token %}
                <div class="form-group">
                    <label for="press_name" class="col-sm-3 control-label">书籍名称</label>
                    <div class="col-sm-9">
                        <input type="text" class="form-control" id="book_name" name="book_name" placeholder="书籍名称">
                    </div>
                </div>

                 <div class="form-group">
                    <label for="press_name" class="col-sm-3 control-label">出版社名称</label>
                    <div class="col-sm-9">
                        <select name="press_id" class="form-control">
                        {% for press in press_data %}
                            <option value="{{ press.id }}">{{ press.name }}</option>
                        {% endfor %}
                    </select>
                    </div>
                </div>

                <div class="form-group">
                    <div class="col-sm-offset-3 col-sm-9">
                        <button type="submit" class="btn btn-default">添加</button>
                    </div>
                </div>
            </form>
        </div>
    </div>
</div>


</body>
</html>

删(跳转页面)

/templates/delete/delete_success.html

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta http-equiv="content-Type" charset="UTF-8">
    <meta http-equiv="x-ua-compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Title</title>
</head>
<body>

<p>删除书籍成功, <span id="s1">3</span>秒钟之后跳转回书籍列表页面!</p>

</body>
<script>
    // 每隔一秒钟就修改s1的text
    var currentNum = document.getElementById('s1').innerText;
    // setInterval(需要做的事情也就是代码段或者是函数,间隔时间)
    // 这样一个对象生成之后需要做一个赋值操作,建立引用和实例之间的联系
    var t2 = setInterval(function () {
        currentNum = document.getElementById('s1').innerText;
        document.getElementById('s1').innerText = currentNum - 1;
        if (currentNum == 1) {
            clearInterval(t2);
            location.href = '/book_list/';
        }
    }, 1000);
</script>
</html>

/templates/edit/edit_book.html

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta http-equiv="content-Type" charset="UTF-8">
    <meta http-equiv="x-ua-compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="/static/bootstrap-3.3.7/css/bootstrap.css">
    <title>编辑书籍</title>
</head>
<body>

<div class="container">
    <div class="row">
        <div class="col-md-6 col-md-offset-3">
            <div class="page-header">
                <h1>编辑书籍</h1>
            </div>
            <form class="form-horizontal" action="/edit_book/?id={{ edit_id }}" method="post">
            {% csrf_token %}
                <div class="form-group">
                    <label for="press_name" class="col-sm-3 control-label">书籍名称</label>
                    <div class="col-sm-9">
                        <input type="text" class="form-control" id="book_name" name="book_name" value="{{ book_name }}">
                    </div>
                </div>

                 <div class="form-group">
                    <label for="press_name" class="col-sm-3 control-label">出版社名称</label>
                    <div class="col-sm-9">
                        <select name="press_id" class="form-control">
                        {% for press in press_list %}
                            <option value="{{ press.id }}">{{ press.name }}</option>
                        {% endfor %}
                    </select>
                    </div>
                </div>

                <div class="form-group">
                    <div class="col-sm-offset-3 col-sm-9">
                        <button type="submit" class="btn btn-default">确认修改</button>
                    </div>
                </div>
            </form>
        </div>
    </div>
</div>


</body>
</html>

注意


ORM变更表结构

ORM修改表结构的时候,执行 python3 manager.py makemigration 时候出来俩选项

 1) Provide a one-off default now (will be set on all existing rows with a null value for this column)
 2) Quit, and let me add a default in models.py

为什么?

给数据库中已经存在的表添加另外一个字段,这个字段既没有默认值也不能为空
ORM就不知道数据库中已经存在的数据该怎么处理这个字段


选项1 是直接在 makemigration跳转到相应的界面自定义默认值, 然后直接执行 migrate命令完成数据库表结构的变更

manage.py@bookmanager > makemigrations
bash -cl "/usr/local/bin/python3.6 /Applications/PyCharm.app/Contents/helpers/pycharm/django_manage.py makemigrations /Users/cjw/Desktop/bookmanager"
Tracking file by folder pattern:  migrations
You are trying to add a non-nullable field 'price' to book without a default; we can't do that (the database needs something to populate existing rows).
Please select a fix:
 1) Provide a one-off default now (will be set on all existing rows with a null value for this column)
 2) Quit, and let me add a default in models.py
Select an option:  1
Please enter the default value now, as valid Python
The datetime and django.utils.timezone modules are available, so you can do e.g. timezone.now
Type 'exit' to exit this prompt
>>> 

选项2 则是退出 makemigration界面, 去models.py中定义相关的字段属性, 完成后回来重新执行 makemigration, 然后再执行migrate


图书管理系统之作者的增删改查


作者表结构设计


1. SQL版
				-- 创建作者表
				create table author(
					id int primary key auto_increment,
					name varchar(32) not null
				);
				
				-- 创建作者和书的关系表
				create table author2book(
					id int primary key auto_increment,
					author_id int not null,
					book_id int not null,
					constraint fk_author foreign key (author_id) references author(id) on delete cascade on update cascade,
					constraint fk_book foreign key (book_id) references book(id) on delete cascade on update cascade
				);


2. ORM版
				1. 第一版:
					自己创建第三张表
    
				2. 第二版
					让ORM帮我们创建第三张表
					models.ManyToManyField()

作者表与书籍表的增删改查


 author_obj = Author.objects.all()

1. 查询
			author_obj.books        --> 得到的只是一个关联关系,并不能拿到数据
			author_obj.books.all()  --> 得到和我这个作者关联的所有书籍对象列表

2. 添加
      author_obj.books.add()  --> 对author_obj这个对象追加外键字段books的值, 传入的值是单列数据类型
      author_obj.books.set()   --> 对author_obj这个对象重新添加外键字段books的值, 传入的值是列表或元组
    
3. 删除
			Author.objects.filter(id=delete_id).delete()
  
3. 编辑
      author_obj.name = author_name
      author_obj.save()
      author_obj.books.set(book_ids)

代码实现

后端业务逻辑

/bookmanager/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'^press_list/', views.press_list),
    url(r'^add_press/', views.add_press),
    url(r'^delete_press/', views.delete_press),
    url(r'^edit_press/', views.edit_press),


    url(r'^book_list/', views.book_list),
    url(r'^add_book/', views.add_book),
    url(r'^delete_book/', views.delete_book),
    url(r'^edit_book/', views.edit_book),

    url(r'author_list/', views.author_list),
    url(r'add_author/', views.add_author),
    url(r'delete_author/', views.delete_author),
    url(r'edit_author/', views.edit_author)

]

/app01/views.py

from django.shortcuts import render, redirect

# Create your views here.

from .models import Press, Book, Author


def author_list(request):
    author_obj = Author.objects.all()
    return render(request, 'list/author_list.html', locals())


def add_author(request):
    book_list = Book.objects.all()

    if request.method == "POST":
        author_name = request.POST.get('author_name')
        book_ids = request.POST.getlist('book_ids')  # request.POST.get 只能获取一个值, request.POST.getlist 能获取多个值, 用列表保存
        author_obj = Author.objects.create(name=author_name)
        author_obj.books.add(*book_ids)  # 参数是一个一个单独的书籍id值
        # author_obj.books.set(book_ids)  # 参数是书籍id值的列表
        return redirect('/author_list/')


    return render(request, 'add/add_author.html', locals())


def delete_author(request):
    delete_id = request.GET.get('id')
    Author.objects.filter(id=delete_id).delete()
    return redirect('/author_list/')


def edit_author(request):
    edit_id = request.GET.get('id')
    author_obj = Author.objects.get(id=edit_id)
    book_list = Book.objects.all()

    if request.method == 'POST':
        author_name = request.POST.get('author_name')
        book_ids = request.POST.getlist('book_ids')
        author_obj.name = author_name
        author_obj.save()
        author_obj.books.set(book_ids)

        return redirect('/author_list/')

    return render(request, 'edit/edit_author.html', locals())

前端页面展示

/templates/list/author_list.html

{% extends 'list/base.html' %}
{% block author %}
active
{% endblock %}
{% block content %}
  <h1 class="page-header">作者列表</h1>

            <!--面板 开始-->
            <div class="panel panel-default">
                <div class="panel-heading">作者列表</div>
                <div class="panel-body">
                    <!--表格上面的那一行-->
                    <div class="row">
                        <div class="col-md-4">
                            <div class="input-group">
                                <input type="text" class="form-control" placeholder="Search for...">
                                <span class="input-group-btn">
                      <button class="btn btn-default" type="button">Go!</button>
                    </span>
                            </div><!-- /input-group -->
                        </div><!-- /.col-lg-6 -->
                        <div class="col-md-1 pull-right">
                            <a class="btn btn-success pull-right" href="/add_author/">添加</a>
                        </div>
                    </div>
                    <!--表格上面那一行 结束-->
                    <!--表格 开始-->
                    <div class="table-box">
                        <table class="table table-bordered table-striped">
                            <thead>
                            <tr>
                                <th class="text-center">序号</th>
                                <th class="text-center">作者id</th>
                                <th class="text-center">作者名字</th>
                                <th class="text-center">所著书籍</th>
                                <th class="text-center">操作</th>
                            </tr>
                            </thead>
                            <tbody>
                            {% for i in author_obj %}
                                <tr class="text-center">
                                    <td>{{ forloop.counter }}</td>
                                    <td>{{ i.id }}</td>
                                    <td>{{ i.name }}</td>
                                    <td>
                                        {% for foo in i.books.all %}
                                            {% if forloop.last %}
                                            《{{ foo.title }}》
                                               {% else %}
                                                《{{ foo.title }}》,
                                            {% endif %}
                                           {% empty %}
                                            暂无作品
                                        {% endfor %}

                                    </td>
                                    <td>
                                        <a class="btn btn-danger btn-sm" href="/delete_author/?id={{ i.id }}">删除</a>
                                        <a class="btn btn-info btn-sm"href="/edit_author/?id={{ i.id }}">编辑</a>
                                    </td>
                                </tr>
                            {% endfor %}
                            </tbody>
                        </table>
                    </div>
                    <!--表格 结束-->
                    <!--分页开始-->
                    <div>
                        <nav aria-label="Page navigation" class="pull-right">
                            <ul class="pagination">
                                <li>
                                    <a href="#" aria-label="Previous">
                                        <span aria-hidden="true">&laquo;</span>
                                    </a>
                                </li>
                                <li><a href="#">1</a></li>
                                <li><a href="#">2</a></li>
                                <li><a href="#">3</a></li>
                                <li><a href="#">4</a></li>
                                <li><a href="#">5</a></li>
                                <li>
                                    <a href="#" aria-label="Next">
                                        <span aria-hidden="true">&raquo;</span>
                                    </a>
                                </li>
                            </ul>
                        </nav>
                    </div>
                    <!--分页结束-->
                </div>
            </div>
            <!--面板 结束-->
{% endblock %}

/templates/add/add_author.html

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta http-equiv="content-Type" charset="UTF-8">
    <meta http-equiv="x-ua-compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="/static/bootstrap-3.3.7/css/bootstrap.css">
    <title>添加书籍</title>
</head>
<body>

<div class="container">
    <div class="row">
        <div class="col-md-6 col-md-offset-3">
            <div class="page-header">
                <h1>添加作者</h1>
            </div>
            <form class="form-horizontal" action="/add_author/" method="post">
            {% csrf_token %}
                <div class="form-group">
                    <label for="author_name" class="col-sm-3 control-label">作者名字</label>
                    <div class="col-sm-9">
                        <input type="text" class="form-control" id="author_name" name="author_name" placeholder="作者名字">
                    </div>
                </div>

                 <div class="form-group">
                    <label for="press_name" class="col-sm-3 control-label">书籍列表</label>
                    <div class="col-sm-9">
                        <select name="book_ids" class="form-control" multiple="multiple">
                        {% for book in book_list %}
                            <option value="{{ book.id }}">{{ book.title }}</option>
                        {% endfor %}
                    </select>
                    </div>
                </div>

                <div class="form-group">
                    <div class="col-sm-offset-3 col-sm-9">
                        <button type="submit" class="btn btn-default">添加</button>
                    </div>
                </div>
            </form>
        </div>
    </div>
</div>


</body>
</html>

/templates/edit/edit_author.html

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta http-equiv="content-Type" charset="UTF-8">
    <meta http-equiv="x-ua-compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="/static/bootstrap-3.3.7/css/bootstrap.css">
    <title>编辑作者</title>
</head>
<body>

<div class="container">
    <div class="row">
        <div class="col-md-6 col-md-offset-3">
            <div class="page-header">
                <h1>编辑作者</h1>
            </div>
            <form class="form-horizontal" action="/edit_author/?id={{ edit_id }}" method="post">
            {% csrf_token %}
                <div class="form-group">
                    <label for="author_name" class="col-sm-3 control-label">作者名字</label>
                    <div class="col-sm-9">
                        <input type="text" class="form-control" id="author_name" name="author_name" value="{{ author_obj.name }}">
                    </div>
                </div>

                 <div class="form-group">
                    <label for="press_name" class="col-sm-3 control-label">书籍名字</label>
                    <div class="col-sm-9">
                        <select name="book_ids" class="form-control" multiple="multiple">
                        {% for book in book_list %}
                            <option value="{{ book.id }}">{{ book.title }}</option>
                        {% endfor %}
                    </select>
                    </div>
                </div>

                <div class="form-group">
                    <div class="col-sm-offset-3 col-sm-9">
                        <button type="submit" class="btn btn-default">确认修改</button>
                    </div>
                </div>
            </form>
        </div>
    </div>
</div>


</body>
</html>

代码下载

gitee仓库

代码下载

posted @ 2019-10-16 22:22  cjw1219  阅读(381)  评论(0编辑  收藏  举报