Django入门实战之图书管理系统

图书管理系统

1.系统介绍

  • 这个图书管理系统,是针对于刚刚学完模板语法ORM单表操作之后的一个小作业

1.1 系统成品预览:

在这里插入图片描述

1.2 系统功能介绍:

  • 1、新增图书 add_book
  • 2、删除图书 delete_book
  • 3、修改图书 change_book
  • 4、查询图书 books

1.3 开发环境:

Python3.6.5
Pycharm2018专业版
Django3.2.3
Bootstrap.css

2.新建项目

  • 2.1 新建一个名为book的Django项目文件和名为app01的应用

在这里插入图片描述
目录结构:

  • book

    • app01: 应用及视图函数目录
    • book: 配置文件及全局相关
    • templates html文件相关
  • 2.2 在MySQL中创建一个名为book的数据库

在这里插入图片描述

  • 2.3 在全局settings.py文件中,配置数据库,代码如下:
# DATABASES = {
#     'default': {
#         'ENGINE': 'django.db.backends.sqlite3',
#         'NAME': BASE_DIR / 'db.sqlite3',
#     }
# }

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'book',  # 要连接的数据库,连接前需要创建好
        'USER': 'root',  # 连接数据库的用户名
        'PASSWORD': '',  # 连接数据库的密码
        'HOST': '127.0.0.1',  # 连接主机,默认本级
        'PORT': 3306  # 端口 默认3306
    }
}

注意: 记得把Django默认的数据库注释掉

  • 2.4 在book文件夹下,与settings.py同级的__init__.py文件中,加入以下代码:
import pymysql

pymysql.install_as_MySQLdb()

  • 为什么要加这两行代码

这是因为django默认你导入的驱动是MySQLdb,可是MySQLdb 对于py3有很大问题,所以我们需要的驱动是PyMySQL,让Django能连接到我们的MySQL数据库

  • 2.5 在app01目录下,models.py文件中,设计表结构:
from django.db import models

# Create your models here.


class Book(models.Model):
    # id = models.AutoField()
    title = models.CharField(max_length=32, unique=True)
    pub_date = models.DateField()
    price = models.DecimalField(max_digits=8, decimal_places=2)
    publish = models.CharField(max_length=32)

注意:

要确认在配置文件中的INSTALLED_APPS中写入我们创建的app名称,然后进行数据库迁移

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'app01.apps.App01Config',
]
  • 2.6 完成上述操作后,进行数据库迁移
python manage.py makemigrations
python manage.py migrate
  • 2.7 在全局urls.py文件中,为图书管理系统配置路由:
from django.contrib import admin
from django.urls import path, re_path
from app01 import views

urlpatterns = [
    path('admin/', admin.site.urls),
    path('addbook/', views.addbook),  # 添加数据url
    path('books/', views.books),  # 查看书籍url
    re_path(r"books/(\d+)/delete", views.delbook),  # 删除书籍url
    re_path(r"books/(\d+)/change", views.changebook),  # 修改书籍url
]
  • 2.8 在views.py文件中,为图书管理系统url路由新建视图函数:
from django.shortcuts import render, HttpResponse, redirect

# Create your views here.
from app01.models import Book


def addbook(request):
    """新增书籍"""
    if request.method == 'POST':
        try:
            title = request.POST.get("title")
            price = request.POST.get("price")
            date = request.POST.get("date")
            publish = request.POST.get("publish")
            Book.objects.create(title=title, price=price, pub_date=date, publish=publish)
            return redirect("/books/")
        except Exception as e:
            print(e)

    return render(request, 'addbook.html')


def books(request):
    """查看书籍"""
    book_list = Book.objects.all()
    return render(request, "books.html", locals())


def delbook(request, id):
    """删除书籍"""
    Book.objects.filter(id=id).delete()
    return redirect("/books/")  # 重定向


def changebook(request, id):
    """编辑书籍"""
    book_obj = Book.objects.filter(id=id).first()
    if request.method == 'POST':
        title = request.POST.get("title")
        price = request.POST.get("price")
        date = request.POST.get("date")
        publish = request.POST.get("publish")

        Book.objects.filter(id=id).update(title=title, price=price, pub_date=date, publish=publish)
        return redirect("/books/")  # 重定向

    return render(request, 'changebook.html', {"book_obj": book_obj})

  • 2.9 在templates文件夹下,为视图函数创建前端页面:

注意:在app01目录下创建一个static的静态文件并把Bootstrap.css文件放进去,然后在HTML中引入Bootstrap.css文件

base.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    {# 引入bootstrap #}
    <link rel="stylesheet" href="/static/bootstrap/css/bootstrap.css">
    <style>
        .container{
            margin-top: 80px;
        }
        .btn{
            margin-top: 10px;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="row">
            <div class="col-md-6 col-md-offset-3">
                {% block header %}

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

</body>
</html>

在这里,我使用了模板继承语法,所以会有一个base.html文件作为父页面,方便子页面继承

books.html

{% extends 'base.html' %}

{% block header %}
    <div style="text-align: center; font-size: 40px;">查看书籍</div>
    <div>
        <a href="/addbook/" class="btn btn-primary">添加书籍</a>
        <table class="table table-striped table-bordered">
            <thead>
            <tr>
                <th>书籍名称</th>
                <th>价格</th>
                <th>出版时间</th>
                <th>出版社</th>
                <th>删除操作</th>
                <th>编辑操作</th>
            </tr>
            </thead>
            <tbody>
            {% for book in book_list %}
                <tr>
                    <td>{{ book.title }}</td>
                    <td>{{ book.price }}</td>
                    <td>{{ book.pub_date|date:'Y-m-d' }}</td>
                    <td>{{ book.publish }}</td>
                    <td><a href="/books/{{ book.pk }}/delete" class="btn btn-danger">删除</a></td>
                    <td><a href="/books/{{ book.pk }}/change" class="btn btn-info">编辑</a></td>
                </tr>
            {% endfor %}
            </tbody>
        </table>
    </div>

{% endblock %}

changebook.html

{% extends 'base.html' %}

{% block header %}
    <div style="text-align: center; font-size: 40px;">修改书籍</div>
    <div>
        <form action="" method="post">
            {% csrf_token %}
            <div>
                <label for="">书籍名称:</label>
                <input type="text" class="form-control" name="title" value="{{ book_obj.title }}">
            </div>
            <div>
                <label for="">价格:</label>
                <input type="text" class="form-control" name="price" value="{{ book_obj.price }}">
            </div>
            <div>
                <label for="">出版日期:</label>
                <input type="date" class="form-control" name="date" value="{{ book_obj.pub_date|date:'Y-m-d' }}">
            </div>
            <div>
                <label for="">出版社:</label>
                <input type="text" class="form-control" name="publish" value="{{ book_obj.publish }}">
            </div>
            <input type="submit" class="btn btn-success pull-right">
        </form>
    </div>
{% endblock %}

addbook.html

{% extends 'base.html' %}

{% block header %}
    <div style="text-align: center; font-size: 40px;">添加书籍</div>
    <div>
        <form action="" method="post">
            {% csrf_token %}
            {#                    {%csrf_token%}这串内容,它的作用是当我们get表单页面时,服务器返回页面的同时也会向前端返回一串随机字符,#}
            {#                    post提交时服务器会验证这串字符来确保用户是在服务端返回的表单页面中提交的数据,防止有人通过例如jquery脚本向某个url不断提交数据,#}
            {#                    是一种数据提交的验证机制。Django的CSRF防御机制。#}
            <div>
                <label for="">书籍名称:</label>
                <input type="text" class="form-control" name="title">
            </div>
            <div>
                <label for="">价格:</label>
                <input type="text" class="form-control" name="price">
            </div>
            <div>
                <label for="">出版日期:</label>
                <input type="date" class="form-control" name="date">
            </div>
            <div>
                <label for="">出版社:</label>
                <input type="text" class="form-control" name="publish">
            </div>
            <input type="submit" class="btn btn-success pull-right">
        </form>
    </div>
{% endblock %}
  • 全部代码敲完之后,运行图书管理系统,就能看到第一张图那样子啦!感谢预览,阿巴阿巴…

总结:

  • 这个小练习到这里就结束啦!总体还是比较简单的!
  • 4
    点赞
  • 39
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值