作者:小小明
Pandas数据处理高手,帮助万名数据从业者解决各类数据处理难题。
Django入门案例:图书管理系统
无需写sql,不需写前端,利用Django自带的Admin和ORM框架就能轻松实现一个多对多表关系的增删改查。
开发流程
版本
Django 3.1.1
python 3.6.12
(django) E:\python_Projects\django_demo>pip show django
Name: Django
Version: 3.1.1
Summary: A high-level Python Web framework that encourages rapid development and clean, pragmatic design.
Home-page: https://www./
Author: Django Software Foundation
Author-email: foundation@
License: BSD-3-Clause
Location: d:\anaconda3\envs\django\lib\site-packages
Requires: pytz, asgiref, sqlparse
Required-by:
(django) E:\python_Projects\django_demo>python -V
Python 3.6.12 :: Anaconda, Inc.
django安装:
pip install Django -i https://pypi.tuna./simple
-i https://pypi.tuna./simple 指定清华镜像源,下载速度更快。
指定 Django 的下载版本(3.1.1 可以改成你要的版本):
pip install Django==3.1.1 -i https://pypi.tuna./simple
创建项目和APP
django-admin startproject booktest
cd booktest
django-admin startapp book_managerment
带路径演示:
(django) E:\python_Projects\django_demo>django-admin startproject booktest
(django) E:\python_Projects\django_demo>cd booktest
(django) E:\python_Projects\django_demo\booktest>django-admin startapp book_managerment
操作后目录结构:
安装应用
在 booktest\booktest\settings.py 中找到INSTALLED_APPS这一项,修改为:
INSTALLED_APPS = [
'django.contrib.admin' ,
'django.contrib.auth' ,
'django.contrib.contenttypes' ,
'django.contrib.sessions' ,
'django.contrib.messages' ,
'django.contrib.staticfiles' ,
'book_managerment'
]
设计模型
表结构:
书籍表 Book :title 、 price 、 pub_date 、 publish(外键,多对一) 、 authors(多对多)
出版社表 Publish :name 、 city 、 email
作者表 Author :name 、 age 、 au_detail、gender 、 tel 、 addr 、 birthday
以下是表格关联说明:
修改booktest\book_managerment\models.py,定义模型类如下:
from django. db import models
class Author ( models. Model) :
name = models. CharField( max_length= 32 )
age = models. SmallIntegerField( )
gender_choices = (
( 0 , "女" ) ,
( 1 , "男" ) ,
( 2 , "保密" ) ,
)
gender = models. SmallIntegerField( choices= gender_choices)
tel = models. CharField( max_length= 32 )
addr = models. CharField( max_length= 64 )
birthday = models. DateField( )
class Book ( models. Model) :
title = models. CharField( max_length= 32 )
price = models. DecimalField( max_digits= 5 , decimal_places= 2 )
pub_date = models. DateField( )
publish = models. ForeignKey( "Publish" , on_delete= models. CASCADE)
authors = models. ManyToManyField( "Author" )
class Publish ( models. Model) :
name = models. CharField( max_length= 32 )
city = models. CharField( max_length= 64 )
email = models. EmailField( )
生成本地数据库文件
生成迁移文件:根据模型类生成创建表的语句 执行迁移:根据第一步生成的语句在数据库中创建表
python manage.py makemigrations
python manage.py migrate
执行后生成的文件:
插入初始数据
使用DataSource打开db.sqlite3文件后,执行以下sql语句:
insert into book_managerment_publish( id, name, city, email)
values ( 1 , "华山出版社" , "华山" , "hs@163.com" ) ,
( 2 , "明教出版社" , "黑木崖" , "mj@163.com" ) ;
insert into book_managerment_author( id, name, age, gender, tel, addr, birthday)
values ( 1 , "令狐冲" , 25 , 1 , 13432335433 , "华山" , "1994-5-23" ) ,
( 2 , "任我行" , 58 , 1 , 13943454554 , "黑木崖" , "1961-8-13" ) ,
( 3 , "任盈盈" , 23 , 0 , 13878934322 , "黑木崖" , "1996-5-20" ) ;
INSERT INTO book_managerment_book( id, title, price, pub_date, publish_id)
VALUES ( 1 , "独孤九剑" , 200 , "2019-1-7" , 1 ) ,
( 2 , "吸星大法" , 180 , "2019-1-7" , 2 ) ,
( 3 , "葵花宝典" , 280 , "2019-3-15" , 2 ) ;
INSERT INTO book_managerment_book_authors( id, book_id, author_id)
VALUES ( 1 , 1 , 1 ) ,
( 2 , 1 , 2 ) ,
( 3 , 2 , 2 ) ;
评论区有位朋友不知道如何使用DataSource,我截了张图:
后台管理
管理界面本地化:
将显示的语言、时间等使用本地的习惯,这里的本地化就是进行中国化,中国大陆地区使用简体中文,时区使用亚洲/上海时区,注意这里不使用北京时区表示 打开booktest/booktest/settings.py文件,找到语言编码、时区的设置项,将内容改为如下:
LANGUAGE_CODE = 'zh-Hans'
TIME_ZONE = 'Asia/Shanghai'
创建管理员:
python manage.py createsuperuser
(我设置用户名密码均为admin)
(django) E:\python_Projects\django_demo\booktest>python manage.py createsuperuser
用户名 (leave blank to use 'think'): admin
电子邮件地址:
Password:
Password (again):
密码跟 用户名 太相似了。
密码长度太短。密码必须包含至少 8 个字符。
这个密码太常见了。
Bypass password validation and create user anyway? [y/N]: y
Superuser created successfully.
注册模型类
打开booktest\booktest\admin.py文件,编写如下代码
from django. contrib import admin
from . models import *
class BookModal ( admin. StackedInline) :
model = Book
@admin. register( Publish)
class PublishAdmin ( admin. ModelAdmin) :
inlines = [ BookModal]
list_display = ( 'id' , 'name' , 'city' , 'email' , 'books' )
fields = ( 'name' , 'city' , 'email' )
list_filter = [ 'city' ]
search_fields = [ 'name' , 'city' ]
def books ( self, obj) :
return [ book. title for book in obj. book_set. all ( ) ]
@admin. register( Book)
class BookAdmin ( admin. ModelAdmin) :
list_display = ( 'id' , 'title' , 'price' , 'pub_date' , "publish_name" , "author" )
fields = ( 'title' , 'price' , 'pub_date' , "authors" )
search_fields = [ 'title' , 'price' , 'pub_date' ]
def author ( self, obj) :
return [ author. name for author in obj. authors. all ( ) ]
def publish_name ( self, obj) :
return obj. publish. name
filter_horizontal = ( 'authors' , )
@admin. register( Author)
class AuthorAdmin ( admin. ModelAdmin) :
list_display = ( 'id' , 'name' , 'age' , 'gender' , 'tel' , 'addr' , 'birthday' , 'books' )
fields = ( 'name' , 'age' , 'gender' , 'tel' , 'addr' , 'birthday' )
list_filter = [ 'gender' ]
search_fields = [ 'name' , 'age' , 'gender' , 'tel' , 'addr' , 'birthday' ]
def books ( self, obj) :
return [ book. title for book in obj. book_set. all ( ) ]
自定义管理页模板
修改booktest/booktest/settings.py中的TEMPLATES的DIRS为指定的路径:
TEMPLATES = [
{
'BACKEND' : 'django.template.backends.django.DjangoTemplates' ,
'DIRS' : [ 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' ,
] ,
} ,
} ,
]
创建目录booktest/templates/admin,将python安装路径下的Lib\site-packages\django\contrib\admin\templates\admin下的base_site.html文件拷贝到该目录下并修改:
修改为如下内容:
{% extends "admin/base.html" %}
{% block title %}图书后台管理系统{% endblock %}
{% block branding %}
< h1 id = " site-name" > < a href = " {% url ' admin:index' %}" > 图书后台管理系统</ a> </ h1>
{% endblock %}
{% block nav-global %}{% endblock %}
启动项目
执行一下命令后:
python manage.py runserver
打开http://127.0.0.1:8000/admin
操作演示
查询所有作者所写的书:
查询每本书所属的出版社和作者:
查询每个出版社所出的书:
修改作者信息:
修改书籍信息,可管理所归属的作者:
修改出版社信息,可管理所出版的每本书:
支持搜索和过滤: