程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

[Django project combat 1] Book management system

編輯:Python

passed last weekDjango的學習後,(Can't see it點擊此處)The meaning of a deep understanding of a framework is to use it directly for development.Here is an example of a simple library management system.其中,Front-end use is more popularBootstrap4框架,The database uses the database of the cloud service due to its convenience,Better to transplant
This time from the front-end to the back-end business logic part,可謂是webAll the work of development is done.Master this and believe you are rightwebDevelopment has enough awareness.You can build your own website in a few hours at the same time!
The part about the code can be obtained by private letter to the blogger,Due to space reasons, the front-end code is no longer posted.The additions, deletions, revisions and inspections are basically the same,The main thing is to consolidateORM模型代碼書寫,做到熟練.當然,There are still various problems in writing and running,I believe everyone can search for the problem,Or leave a comment to try to understand this simple management!

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

There will be a separate issue about project deployment,In addition, the source code of the project can be obtained by private letter bloggers.

目錄

  • Profiling and database design
  • 效果圖
  • 創建djangoThe project is connected to the database
  • Django模型定義
  • 功能模塊實現
    • Create an imprint view
    • Publisher added
    • Edited by the publisher
    • 刪除出版社
    • 增刪改查(Author view function)
    • 增刪改查(圖書信息)
    • 注冊登錄功能實現

Profiling and database design

The library management system,It is divided into three management system terminals,Information about the publisher,作者信息,圖書信息管理.There are login and registration interfaces at the same time.
數據庫實體設計:
出版社(出版社編號,出版社地址,出版社名稱)
圖書(序號,圖書名稱,圖書編號,譯者,出版日期,出版社)
譯者(序號,姓名,性別,年齡,聯系方式)
作者(序號,用戶名,密碼,郵箱,手機)

效果圖

This is an overview of all the documents for this project.It can be seen that the structure is relatively clear,app01就是app部分(視圖),bmsis the configuration part(路由),staticA front-end framework is usedbootstrap4,templates是前端頁面.運行入口是manage.py.在test.pyParts are test parts or some script workspaces.

部分運行截圖

創建djangoThe project is connected to the database

新建空項目,並在終端輸入

django-admin startproject bms

在數據庫中創建數據庫library

create database library

在settings.py配置數據庫相關設置

# 默認初始:
DATABASES = {

'default': {

'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}
需要修改:
DATABASES = {

'default': {

'ENGINE': 'django.db.backends.mysql', # 數據庫引擎
'NAME': 'library', # 數據庫名稱
'HOST': '**********', # 服務器地址,If it is local, it can be written127.0.0.1
'PORT': 3306,
'USER':'root',
'PASSWORD':'[email protected]',
}
}

在/bms/init.py文件下:

import pymysql
pymysql.install_as_MySQLdb()

The above initialization work has been completed

Django模型定義

模型使用自帶的ORM,It acts as a bridge between the business layer and the database layer.ORM將python代碼轉換成sql語句,sql語句通過pymysqlto the server database,數據庫執行SQL語句.
django規定,如果要使用模型,必須要創建一個app,使用以下命令創建app01的app

python3 manage.py startapp app01

The current folder workspace:

同時在/bms/settings.py中installed_apps添加app01

現在定義模型了.
One has been created beforelibrary數據庫了,現在用python來進行sql語句創建.
注意djangoThere is a mapping relationship between the model and the target database,If you build a table in your own database, it will not necessarily matchdjango規則,As a result, the model cannot be connected to the target database.下面在app01/models.pyCreate content about the table

from django.db import models
# Create your models here.
# 出版社類
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)
# Author's class
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)
# Django Create a foreign key join table operation
tel = models.CharField('聯系方式', max_length=64)
# An author can correspond to multiple books,一本書也可以有多個作者,多對多,Create a third table in the database
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)

Use the command below to make the command create the contents of the table:

python manage.py migrate

If you see the following interface, the operation is successful,如果沒有成功,請關注pymysql,mysql-connector模塊安裝,當然注意init.py文件下的操作(見上)

終端輸入:

python manage.py makemigrations app01
python manage.py migrate app01


在pycharmBelow the database in the professional version,可以看到libraryThe following table has been created.

功能模塊實現

前端框架選用Bootstrap4,它是基於Html css javascript,使得web開發快捷.
在項目根目錄下新建一個static,Used to store front-end template static resources,At the same time, import front-end resources.同時新建templates,用於存放前
This is the current front-end framework file.
打開/bms/settings.py 修改djangoIdentify static resources and template web addresses,找到templatesThe configuration is modified to be used to identify the template page URL.

'DIRS': [os.path.join(BASE_DIR,'templates')], # 只要添加dirs這一項就可以了.

在static_url下面添加:

STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'static'), # 添加此項
]

Create an imprint view

在app01/views.pyCreate an imprint view

from django.shortcuts import render
import models
# Create your views here.
# Publisher Display List
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中寫入前端代碼:

(The front-end code is not put here)

Publisher added

/app01/views.py
Added publisher view

# 添加出版社
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.htmlAdd front-end code:
Front-end code is not given,比較多.

Edited by the publisher

Create and modify the publisher view function
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),

增刪改查(Author view function)

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加密, Here the password is not saved in plaintext,一般來說,This password protection is currently used.
views.py

# 密碼加密 md5加密
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), # 注冊

以上基於djangoThe business part of the library management system has been completed,If you need a private message about the front-end code, please contact us.
Hope to get something!


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved