[django项目实战1]图书管理系统

在上周经过了Django的学习后,(没看到可以点击此处)深入理解一个框架的意义就是直接使用其来进行开发。这里以简单的图书管理系统为例。其中,前端使用的是比较流行的Bootstrap4框架,数据库由于便捷性使用的是云服务的数据库,比较好移植运行
本次从前端到后端业务逻辑部分,可谓是web开发的全部工作了。掌握这篇相信你对web开发有足够的认识了。同时几小时就可以建造自己的网站了!
关于代码部分可以私信博主获得,或者你可以咸鱼上搜我的用户名 MTK3 ,宝贝里面有django图书管理系统哦~欢迎大家前来学习!,由于篇幅原因就不再贴前端代码了。增删改查部分都基本一致,主要也是巩固ORM模型代码书写,做到熟练。当然,编写与运行中仍然会遇到种种问题,相信大家可以通过搜索问题,或者评论留言争取把这个简易的管理搞懂吧!

本地环境 python 3.7.9. Pycharm 2022 Django 3.2 Mysql 5.7 Bootstrap4

关于项目部署将单独做一期,另外项目源码可私信博主获取。

目录

概要分析与数据库设计

本次图书管理系统,分为三个管理系统端,分别是出版社信息,作者信息,图书信息管理。同时有登录和注册界面。
数据库实体设计:
出版社(出版社编号,出版社地址,出版社名称)
图书(序号,图书名称,图书编号,译者,出版日期,出版社)
译者(序号,姓名,性别,年龄,联系方式)
作者(序号,用户名,密码,邮箱,手机)

效果图

这是本次项目的全部文件概览。可以看到结构是比较清晰的,app01就是app部分(视图),bms就是配置部分(路由),static使用的是前端框架bootstrap4,templates是前端页面。运行入口是manage.py。在test.py部分是测试部分或者是一些脚本工作区。

[django项目实战1]图书管理系统
部分运行截图
[django项目实战1]图书管理系统
[django项目实战1]图书管理系统

; 创建django项目与数据库连接

新建空项目,并在终端输入

django-admin startproject bms

在数据库中创建数据库library

CREATE DATABASE IF NOT EXISTS library DEFAULT CHARSET utf8;

在settings.py配置数据库相关设置


DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': BASE_DIR / 'db.sqlite3',
    }
}
需要修改:
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'library',
        'HOST': '**********',
        'PORT': 3306,
        'USER':'root',
        'PASSWORD':'P@ssw0rd',
    }
}

templates={
'DIRS': [os.path.join(BASE_DIR, 'templates')],
}

在/bms/ init.py文件下:

import pymysql

pymysql.install_as_MySQLdb()

以上初始化工作已经完成

Django模型定义

模型使用自带的ORM,在业务层与数据库层充当了桥梁的作用。ORM将python代码转换成sql语句,sql语句通过pymysql传到服务器数据库中,数据库执行SQL语句。
django规定,如果要使用模型,必须要创建一个app,使用以下命令创建app01的app

python3 manage.py startapp app01

目前现在的文件夹工区:

[django项目实战1]图书管理系统
同时在/bms/settings.py中installed_apps添加app01

现在 定义模型了。
之前已经创建一个library数据库了,现在用python来进行sql语句创建。
注意django对模型和目标数据库有映射关系,如果在自己的数据库建表会存在不一定符合django规则,从而导致模型与目标数据库无法连接。下面在app01/models.py创建关于表的内容

建表命令:
CREATE DATABASE IF NOT EXISTS library DEFAULT CHARSET utf8;
from django.db import models

class Publisher(models.Model):
    id = models.AutoField('序号',primary_key=True)
    name = models.CharField('名称',max_length=64)
    addr = models.CharField('地址',max_length=64)

class Book(models.Model):
    id = models.AutoField('序号',primary_key=True)
    name = models.CharField('名称',max_length=64,null=True)
    ISBN = models.CharField('编号',max_length=64)
    translator = models.CharField('译者',max_length=64)
    translator = models.CharField('译者', max_length=64)
    date = models.DateField('出版日期', max_length=64, blank=True)
    publisher = models.ForeignKey(to=Publisher, on_delete=models.CASCADE)

class Author(models.Model):
    id = models.AutoField('序号', primary_key=True)
    name = models.CharField('姓名', max_length=64)
    sex = models.CharField('性别', max_length=4)
    age = models.IntegerField('年龄', default=0)

    tel = models.CharField('联系方式', max_length=64)

    book = models.ManyToManyField(to=Book)

class LmsUser(models.Model):
    id = models.AutoField('序号', primary_key=True)
    username = models.CharField('用户名', max_length=32)
    password = models.CharField('密码', max_length=32)
    email = models.EmailField('邮箱')
    mobile = models.IntegerField('手机', max_length=11)

下面使用命令使得命令创建表的内容:

//如果在app01/migrations 有除了__init__.py以外的文件,那么先删掉然后使用命令
python manage.py flush

python manage.py migrate

看到如下界面表示运行成功了,如果没有成功,请关注pymysql,mysql-connector模块安装,当然注意init.py文件下的操作(见上)

[django项目实战1]图书管理系统
终端输入:
python manage.py makemigrations app01
python manage.py migrate app01

[django项目实战1]图书管理系统
在pycharm专业版中的数据库下面,可以看到library已经创建了如下表。
[django项目实战1]图书管理系统

功能模块实现

前端框架选用Bootstrap4,它是基于Html css javascript,使得web开发快捷。

[django项目实战1]图书管理系统
这是目前的前端框架文件。
打开/bms/settings.py 修改django识别静态资源和模版网页地址,找到templates配置修改为用于识别模版网页网址。
'DIRS': [os.path.join(BASE_DIR,'templates')],

在static_url下面添加:

STATICFILES_DIRS = [
    os.path.join(BASE_DIR, 'static'),
]

创建出版社视图

在app01/views.py创建出版社视图

from django.shortcuts import render
import models

def publisher_list(request):
    publisher = models.Publisher.objects.all()
    return render(request,'pub_list.html',{'pub_list':publisher})

在urls.py配置路由信息

from django.contrib import admin
from django.urls import path
from django.conf.urls import url

from ..app01 import  views

urlpatterns = [
    path('admin/', admin.site.urls),
    path(r'^pub_list/',views.publisher_list)
]

在templates/pub_list.html中写入前端代码:

(前端代码就不放这里了)

出版社新增

/app01/views.py
新增出版社视图


def add_publisher(request):
    if request.method == 'POST':
        new_publisher_name = request.POST.get('name')
        new_publisher_addr = request.POST.get('addr')
        models.Publisher.objects.create(name=new_publisher_name,addr=new_publisher_addr)
        return redirect('/pub_list/')
    return render(request,'pub_add.html')

修改urls.py映射关系

url(r'^add_pub/',views.add_publisher)

在/templates/pub_add.html新增前端代码:
前端代码就不给了,比较多。

出版社修改

创建修改出版社视图函数
views.py

def edit_publisher(request):
    if request.method == 'POST':
        edit_id = request.GET.get('id')
        edit_obj = models.Publisher.objects.get(id=edit_id)
        new_name = request.POST.get('edit_name')
        new_addr = request.POST.get('edit_addr')
        edit_obj.name=new_name
        edit_obj.addr=new_addr
        edit_obj.save()
        return  redirect('/pub_list/')

    edit_id = request.GET.get('id')
    edit_obj = models.Publisher.objects.get(id=edit_id)
    return  render(request,'pub_edit.html',{'publisher':edit_obj})

urls.py

url(r'^edit_pub/',views.edit_publisher),

templates/pub_edit.html

删除出版社

views.py


def drop_publisher(request):
    drop_id = request.GET.get('id')
    drop_obj = models.Publisher.objects.get(id=drop_id)
    drop_obj.delete()
    return redirect('/pub_list/')

urls.py

url(r'^drop_pub/', views.drop_publisher),

增删改查(作者视图函数)

views.py


def add_author(request):
    if request.method == 'POST':
        new_author_name = request.POST.get('name')
        new_author_sex = request.POST.get('sex')
        new_author_age = request.POST.get('age')
        new_author_tel = request.POST.get('tel')
        models.Author.objects.create(name=new_author_name, sex=new_author_sex, age=new_author_age, tel=new_author_tel)
        return redirect('/author_list/')
    return render(request, 'author_add.html')

def drop_author(request):
    drop_id = request.GET.get('id')
    drop_obj = models.Author.objects.get(id=drop_id)
    drop_obj.delete()
    return redirect('/author_list/')

def edit_author(request):
    if request.method == 'POST':
        edit_id = request.GET.get('id')
        edit_obj = models.Author.objects.get(id=edit_id)
        new_author_name = request.POST.get('edit_name')
        new_author_sex = request.POST.get('edit_sex')
        new_author_age = request.POST.get('edit_age')
        new_author_tel = request.POST.get('edit_tel')
        new_book_id = request.POST.getlist('book_id')
        edit_obj.name = new_author_name
        edit_obj.sex = new_author_sex
        edit_obj.age = new_author_age
        edit_obj.tel= new_author_tel
        edit_obj.book.set(new_book_id)
        edit_obj.save()
        return redirect('/author_list/')
    edit_id = request.GET.get('id')
    edit_obj = models.Author.objects.get(id=edit_id)
    all_book = models.Book.objects.all()
    return render(request, 'auth_edit.html', {
        'author': edit_obj,
        'book_list': all_book
    })

urls.py

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

增删改查(图书信息)

views.py


def book_list(request):
    book = models.Book.objects.all()
    return render(request, 'book_list.html', {'book_list': book})

def add_book(request):
    if request.method == 'POST':
        new_book_name = request.POST.get('name')
        new_book_ISBN = request.POST.get('ISBN')
        new_book_translator = request.POST.get('translator')
        new_book_date = request.POST.get('date')
        publisher_id = request.POST.get('publisher_id')
        models.Book.objects.create(name=new_book_name, publisher_id=publisher_id, ISBN=new_book_ISBN,
                                   translator=new_book_translator, date=new_book_date)
        return redirect('/book_list/')
    res = models.Publisher.objects.all()
    return render(request, 'book_add.html', {'publisher_list': res})

def drop_book(request):
    drop_id = request.GET.get('id')
    drop_obj = models.Book.objects.get(id=drop_id)
    drop_obj.delete()
    return redirect('/book_list/')

def edit_book(request):
    if request.method == 'POST':
        new_book_name = request.POST.get('name')
        new_book_ISBN = request.POST.get('ISBN')
        new_book_translator = request.POST.get('translator')
        new_book_date = request.POST.get('date')
        new_publisher_id = request.POST.get('publisher_id')
        edit_id = request.GET.get('id')
        edit_obj = models.Book.objects.get(id=edit_id)
        edit_obj.name = new_book_name
        edit_obj.ISBN = new_book_ISBN
        edit_obj.translator = new_book_translator
        edit_obj.date = new_book_date
        edit_obj.publisher_id = new_publisher_id
        edit_obj.save()
        return redirect('/book_list/')
    edit_id = request.GET.get('id')
    edit_obj = models.Book.objects.get(id=edit_id)
    all_publisher = models.Publisher.objects.all()
    return render(request, 'book_edit.html', {'book': edit_obj, 'publisher_list': all_publisher})

urls.py

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

注册登录功能实现

密码使用的是md5加密, 这里是密码没有进行明文保存的,一般来说,目前都是使用这种的密码保护。
views.py


def setPassword(password):
    md5 = hashlib.md5()
    md5.update(password.encode())
    password = md5.hexdigest()
    return str(password)

def login(request):
    if request.method == 'POST' and request.POST:
        email = request.POST.get("email")
        password = request.POST.get("password")
        e = LmsUser.objects.filter(email=email).first()
        if e:
            now_password = setPassword(password)
            db_password = e.password
            if now_password == db_password:
                reponse = HttpResponseRedirect('/pub_list/')
                reponse.set_cookie("username",e.username)
                return reponse
    return render(request,"login.html")

def register(request):
    if request.method == "POST" and request.POST:
        data = request.POST
        username = data.get("username")
        email = data.get("email")
        password= data.get("password")
        mobile = data.get("mobile")
        LmsUser.objects.create(
            username = username,
            email = email,
            password = setPassword(password),
            mobile = mobile,
        )
        return  HttpResponseRedirect('/login/')
    return render(request,"register.html")

urls.py

    url(r'^login/', views.login),
    url(r'^signup/', views.register),
    url(r'^register/', views.register),

以上基于django的图书管理系统的业务部分已经全部完成了,关于前端代码有需要的私信联系。
希望有所收获哦!

Original: https://blog.csdn.net/QAZJOU/article/details/126100420
Author: 三金C_C
Title: [django项目实战1]图书管理系统

原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/671031/

转载文章受原作者版权保护。转载请注明原作者出处!

(0)

大家都在看

亲爱的 Coder【最近整理,可免费获取】👉 最新必读书单  | 👏 面试题下载  | 🌎 免费的AI知识星球