图书管理系统
1 创建django项目和所需数据库booksystem
# 1 运行docker mysql容器并进入容器创建数据库
docker run -itd --name mysql -p 3306:3306 -e MYSQL_ROOT_PASSWORD=123456 [mysql镜像id]
docker exec -it mysql env LANG=C.UTF-8 /bin/bash
mysql -uroot -p123456
create database booksystem default charset=utf8;
# 2 安装django版本及创建项目
pip install django==2.1.2
django-admin startproject booksystem
2 创建app01
cd booksystem
python manage.py startapp app01
3 booksystem/settings.py 配置
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'app01'
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
# 'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
import os
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR,'templates')],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
# Database
# https://docs.djangoproject.com/en/2.1/ref/settings/#databases
DATABASES = {
'default':
{
'ENGINE': 'django.db.backends.mysql',
'NAME': 'booksystem', # 数据库的名字
'USER': 'root', # 登录数据库的用户名
'PASSWORD': '123456', # 登录数据库的密码
'HOST': '127.0.0.1', # 数据库的IP地址
'PORT': '3306', # 数据库的端口
}
}
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'handlers': {
'console':{
'level':'DEBUG',
'class':'logging.StreamHandler',
},
},
'loggers': {
'django.db.backends': {
'handlers': ['console'],
'propagate': True,
'level':'DEBUG',
},
}
}
4 booksystem/urls.py 配置
from django.contrib import admin
from django.urls import path,include,re_path
from app01 import views
urlpatterns = [
path('admin/', admin.site.urls),
path('index/', views.create_data),
path('add_book/', views.add_book),
path('read_book/', views.read_book),
re_path('books/(\d+)/change/', views.edit_book),
re_path('books/(\d+)/delete/', views.delete_book),
]
5 app01/models.py 配置
from django.db import models
# 作者详情表
class MsgDetail(models.Model):
nid = models.AutoField(primary_key=True)
birthday = models.DateField()
telephone = models.BigIntegerField()
address = models.CharField(max_length=64)
class Meta(object):
db_table = 'msgdetail'
# 作者详情页
class Author(models.Model):
nid = models.AutoField(primary_key=True)
name = models.CharField(max_length=32)
age = models.IntegerField()
msgdetail = models.OneToOneField(to='MsgDetail',to_field='nid',on_delete=models.CASCADE)
class Meta(object):
db_table = 'author'
# 出版社表
class Publish(models.Model):
nid = models.AutoField(primary_key=True)
name = models.CharField(max_length=32)
city = models.CharField(max_length=32)
email = models.EmailField()
class Meta(object):
db_table = 'publish'
# 书籍表
class Book(models.Model):
nid = models.AutoField(primary_key=True)
title = models.CharField(max_length=32)
publishDate = models.DateField()
price = models.DecimalField(max_digits=5,decimal_places=2)
read_number = models.IntegerField(default=20)
comment_number = models.IntegerField(default=20)
# 一对多
# 关联字段 django会自动拼接id publish --->️ publish_id
publish = models.ForeignKey(to='Publish', to_field='nid',on_delete=models.CASCADE,null=True) # 外键值可以为空
# 多对多,执行完创建第三张表:book2author
authors = models.ManyToManyField(to='Author')
def __str__(self):
return self.title
class Meta(object):
db_table = 'book'
6 app01/views.py 配置
from django.shortcuts import render,HttpResponse,redirect
from .models import *
def create_data(request):
# 1 添加数据 MsgDetail
ret = MsgDetail.objects.create(birthday='2001-04-01', telephone=10010, address='china port')
ret = MsgDetail.objects.create(birthday='2011-02-01', telephone=15532634791, address='shunfeng port')
ret = MsgDetail.objects.create(birthday='2011-12-01', telephone=15532634791, address='yuantong port')
# 2 Author
ret = Author.objects.create(nid=1, name='alex', age=33, msgdetail_id=1)
ret = Author.objects.create(nid=2, name='egon', age=43, msgdetail_id=2)
# 3 Publish
ret = Publish.objects.create(name='Peoples Publishing', email='15532634791@163.com', city='beijing')
ret = Publish.objects.create(name='hebei Publish', email='wangze@163.com', city='hebei')
ret = Publish.objects.create(name='xian Publish', email='wangze@163.com', city='xian')
#
# """ --------------- 4 BOOK --------------- """
# # 方式一: 以数据库中字段插入数据
book_obj = Book.objects.create(title='Python', publishDate='2001-04-01', price=200, publish_id=1)
book_obj = Book.objects.create(title='java', publishDate='2001-04-01', price=230, publish_id=2)
book_obj = Book.objects.create(title='php', publishDate='2001-04-01', price=190, publish_id=3)
# 方式二
pub_obj = Publish.objects.filter(nid=1).first()
book_obj = Book.objects.create(title='C++', publishDate='2001-04-01', price=221, publish=pub_obj)
# # --------------- 5 book_authors ---------------
# # 添加多对多关系
alex = Author.objects.get(name='alex')
egon = Author.objects.get(name='egon')
book_obj = Book.objects.filter(title='Python').first()
book_obj.authors.add(alex, egon)
return HttpResponse('添加数据')
def add_book(request):
if request.method.lower()== 'post':
title = request.POST.get('title')
price = request.POST.get('price')
pub_date = request.POST.get('pub_date')
publish_id = request.POST.get('publish_id')
author_id_list = request.POST.getlist('authors_id_list')
# 添加书籍
book_obj = Book.objects.create(title=title,price=price,publishDate=pub_date,publish_id=publish_id)
# 绑定添加多对多关系
book_obj.authors.add(*author_id_list)
# INSERT INTO `book_authors` (`book_id`, `author_id`) VALUES (13, 2), (13, 1);
return HttpResponse('123')
publish_list = Publish.objects.all()
author_list = Author.objects.all()
return render(request,'add_book.html',locals())
def read_book(request):
book_list = Book.objects.all()
return render(request,'read_book.html',locals())
def edit_book(request,edit_book_id):
edit_book_obj = Book.objects.filter(pk=edit_book_id).first()
if request.method.lower()== 'post':
title = request.POST.get('title')
price = request.POST.get('price')
pub_date = request.POST.get('pub_date')
publish_id = request.POST.get('publish_id')
author_id_list = request.POST.getlist('authors_id_list')
Book.objects.filter(pk=edit_book_id).update(title=title,price=price,publishDate=pub_date,publish_id=publish_id)
# edit_book_obj.authors.clear()
# edit_book_obj.authors.add(*author_id_list)
# set 先清空后设置
edit_book_obj.authors.set(author_id_list)
return redirect('/read_book/')
publish_list = Publish.objects.all()
author_list = Author.objects.all()
return render(request,'edit_book.html',locals())
def delete_book(request,delete_book_id):
Book.objects.filter(pk=delete_book_id).delete()
return redirect('/read_book/')
7 templates/add_book.html 文件
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<link href="https://cdn.bootcss.com/twitter-bootstrap/2.3.2/css/bootstrap.min.css" rel="stylesheet">
<link href="https://cdn.jsdelivr.net/npm/@bootcss/v3.bootcss.com@1.0.10/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<center> <h3> 添加书籍 📚 </h3> </center>
<div class="container">
<div class="row">
<div class="col-md-6 col-md-offset-3">
<form action="" method="post">
{% csrf_token %}
<div class="form-group">
<label for="">书籍名称</label>
<input type="text" class="form-control" name="title">
</div>
<div class="form-group">
<label for="">价格</label>
<input type="text" class="form-control" name="price">
</div>
<div class="form-group">
<label for="">出版日期</label>
<input type="date" class="form-control" name="pub_date">
</div>
<div class="form-group">
<label for="">出版社</label>
<select name="publish_id" class="form-control">
{% for publish in publish_list%}
<option value="{{ publish.pk }}"> {{ publish.name }} </option>
{% endfor %}
</select>
</div>
<div class="form-group">
<label for="">作者</label>
<select name="authors_id_list" class="form-control" multiple>
{% for author in author_list%}
<option value="{{ author.pk }}"> {{ author.name }} </option>
{% endfor %}
</select>
</div>
<input type="submit" class="btn btn-success pull-right">
<a href="/read_book" class="btn btn-primary"> 查看书籍 </a>
</form>
</div>
</div>
</div>
</body>
</html>
8 templates/edit_book.html 文件
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<link href="https://cdn.bootcss.com/twitter-bootstrap/2.3.2/css/bootstrap.min.css" rel="stylesheet">
<link href="https://cdn.jsdelivr.net/npm/@bootcss/v3.bootcss.com@1.0.10/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<center> <h3> 编辑书籍 📚 </h3> </center>
<div class="container">
<div class="row">
<div class="col-md-6 col-md-offset-3">
<form action="" method="post">
{% csrf_token %}
<div class="form-group">
<label for="">书籍名称</label>
<input type="text" class="form-control" name="title" value="{{ edit_book_obj.title }}">
</div>
<div class="form-group">
<label for="">价格</label>
<input type="text" class="form-control" name="price" value="{{ edit_book_obj.price }}">
</div>
<div class="form-group">
<label for="">出版日期</label>
<input type="date" class="form-control" name="pub_date" value="{{ edit_book_obj.publishDate|date:'Y-m-d' }}">
</div>
<div class="form-group">
<label for="">出版社</label>
<select name="publish_id" class="form-control">
{% for publish in publish_list%}
{% if edit_book_obj.publish == publish %}
<option selected value="{{ publish.pk }}"> {{ publish.name }} </option>
{% else %}
<option value="{{ publish.pk }}"> {{ publish.name }} </option>
{% endif %}
{% endfor %}
</select>
</div>
<div class="form-group">
<label for="">作者</label>
<select name="authors_id_list" class="form-control" multiple>
{% for author in author_list%}
{% if author in edit_book_obj.authors.all %}
<option selected value="{{ author.pk }}"> {{ author.name }} </option>
{% else %}
<option value="{{ author.pk }}"> {{ author.name }} </option>
{% endif %}
{% endfor %}
</select>
</div>
<input type="submit" class="btn btn-success pull-right">
<a href="/read_book" class="btn btn-primary"> 查看书籍 </a>
</form>
</div>
</div>
</div>
</body>
</html>
9 templates/read_book.html 文件
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<link href="https://cdn.bootcss.com/twitter-bootstrap/2.3.2/css/bootstrap.min.css" rel="stylesheet">
<link href="https://cdn.jsdelivr.net/npm/@bootcss/v3.bootcss.com@1.0.10/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<center> <h3> 查看书籍 📚 </h3>
<a href="/add_book/" class="btn btn-primary">添加书籍</a>
</center>
<div class="container">
<div class="row">
<div class="col-md-8 col-md-offset-2">
<table class="table table-bordered table-hover table-striped">
<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.price }} </td>
<td> {{ book.publishDate|date:'Y-m-d' }} </td>
<td> {{ book.publish.name }} </td>
<td>
{% for author in book.authors.all %}
{% if forloop.last %}
<span>{{ author.name }}</span>
{% else %}
<span>{{ author.name }}</span>,
{% endif %}
{% endfor %}
</td>
<td>
<a href="/books/{{ book.pk }}/change/" class="btn btn-primary">编辑</a>
<a href="/books/{{ book.pk }}/delete/" class="btn btn-danger">删除</a>
</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
</div>
</div>
</body>
</html>
10 数据库迁移并生成数据表
python manage.py makemigrations
python manage.py migrate
11 运行项目
python manage.py runserver 0.0.0.0:8000
12 数据准备
首先访问index 创建数据