Django(图书管理系统)
图书管理系统
注意事项
1、models 要创建好,规划好自己的表,以及各种表关系
2、url正则要写好
3、settings的配置
4、利用bootstarp 进行布局更漂亮哦
5、注意orm 各种类型的转换还有取值。
6、模板语法
下面上菜
目录结构
G:.
├─.idea
│ ├─dataSources
│ └─inspectionProfiles
├─app01
│ ├─migrations
│ │ └─__pycache__
│ ├─static
│ │ └─css
│ └─__pycache__
├─books
│ └─__pycache__
└─templates
项目代码
settings.py
""" Django settings for books project.Generated by 'django-admin startproject' using Django 2.0.2.For more information on this file, see https://docs.djangoproject.com/en/2.0/topics/settings/For the full list of settings and their values, see https://docs.djangoproject.com/en/2.0/ref/settings/ """import os# Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))# Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.0/howto/deployment/checklist/# SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'm-zu@pls$#8)6njw1ar5#t#tx#fcfhe7(iaygkg(y4l^x@!!ix'# SECURITY WARNING: don't run with debug turned on in production! DEBUG = TrueALLOWED_HOSTS = []# Application definition INSTALLED_APPS = ['django.contrib.admin','django.contrib.auth','django.contrib.contenttypes','django.contrib.sessions','django.contrib.messages','django.contrib.staticfiles','app01.apps.App01Config', ]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', ]ROOT_URLCONF = 'books.urls'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',],},}, ]WSGI_APPLICATION = 'books.wsgi.application'# Database # https://docs.djangoproject.com/en/2.0/ref/settings/#databases# DATABASES = {# 'default': {# 'ENGINE': 'django.db.backends.sqlite3', # 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), # } # } DATABASES = {'default': {'ENGINE': 'django.db.backends.mysql','NAME': 'books','HOST': '172.16.0.30','PORT': '3306','USER': 'root','PASSWORD': 'zabbix',} }# Password validation # https://docs.djangoproject.com/en/2.0/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [{'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',},{'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',},{'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',},{'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',}, ]# Internationalization # https://docs.djangoproject.com/en/2.0/topics/i18n/ LANGUAGE_CODE = 'en-us'TIME_ZONE = 'UTC'USE_I18N = TrueUSE_L10N = TrueUSE_TZ = True# Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/2.0/howto/static-files/ STATIC_URL = '/static/' LOGGING = {'version': 1,'disable_existing_loggers': False,'handlers': {'console': {'level': 'DEBUG','class': 'logging.StreamHandler',},},'loggers': {'django.db.backends': {'handlers': ['console'],'propagate': True,'level': 'DEBUG',},} }
urls.py
"""books URL ConfigurationThe `urlpatterns` list routes URLs to views. For more information please see:https://docs.djangoproject.com/en/2.0/topics/http/urls/ Examples: Function views1. Add an import: from my_app import views2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based views1. Add an import: from other_app.views import Home2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf1. Import the include() function: from django.urls import include, path2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) """ from django.contrib import admin from django.urls import path from app01 import views from django.conf.urls import urlurlpatterns = [path('admin/', admin.site.urls),path('index', views.index),url(r'^editbooks/(?P<nid>[0-9]*)/edit$', views.editbooks, name='editbooks'),url(r'^books/(?P<nid>[0-9]*)/delete$', views.delete, name='delete'),url(r'^books/$', views.books),url(r'^addbooks/', views.addbooks, name='addbooks'),]
views.py
from django.shortcuts import HttpResponse, render, redirect, HttpResponseRedirect from .models import * import decimal from django.db.models import Avg, Sum, Count, Max, Min, F, Qdef index(request):return HttpResponse('ok')def books(request):book_list = Book.objects.all()author_list = Author.objects.all()publish_list = Publish.objects.all()return render(request, 'books.html', {'book_list': book_list, 'author': author_list, 'publish_list': publish_list})def delete(request, nid):book_obj = Book.objectsprint('_________________________________________________________')print(nid)book_obj.filter(nid=nid).delete()print('删除成功')return redirect('/books')def addbooks(request):author_list = Author.objects.all()publish_list = Publish.objects.all()if request.method == 'GET':return render(request, 'addbooks.html', {'publish_list': publish_list, 'author_list': author_list})else:try:title = request.POST.get('title')price = int(request.POST.get('price'))pub_date = request.POST.get('pub_date')publish_id = request.POST.get('publish_id')autho_id_list = request.POST.getlist('author_id_list') # 当获取多个数值的时候,使用getlistbook_obj = Book.objects.create(title=title, price=price, publishDate=pub_date, publish_id=publish_id)book_obj.authors.add(*autho_id_list)except Exception as e:print(e, '数值郭达')return redirect('/addbooks')return redirect('/books')def editbooks(request, nid):author_list = Author.objects.all()publish_list = Publish.objects.all()book_nid_obj = Book.objects.get(nid=nid)if request.method == 'GET':return render(request, 'editbooks.html',{'author_list': author_list, 'book_nid_obj': book_nid_obj,'publish_list': publish_list})else:# 编辑操作title = request.POST.get('title')price = int(request.POST.get('price'))pub_date = request.POST.get('pub_date')publish_id = request.POST.get('publish_id')author_id_list = request.POST.getlist('author_id_list') # 当获取多个数值的时候,使用getlistprint(request.POST)book_obj_ed = Book.objects.filter(nid=nid)print(book_nid_obj) # Book 对象print('--------------------------------------------')print(book_obj_ed) # QueySetbook_obj_ed.update(title=title, price=price, publishDate=pub_date, publish_id=publish_id)book_nid_obj.authors.clear()book_nid_obj.authors.add(*author_id_list)return redirect('/books')
models.py
from django.db import models# Create your models here.class Author(models.Model):nid = models.AutoField(primary_key=True)name = models.CharField(max_length=32)age = models.IntegerField()# 与AuthorDetail建立一对一的关系authorDetail = models.OneToOneField(to="AuthorDetail", on_delete=models.CASCADE)class AuthorDetail(models.Model):nid = models.AutoField(primary_key=True)birthday = models.DateField()telephone = models.BigIntegerField()addr = models.CharField(max_length=64)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 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)# 与Publish建立一对多的关系,外键字段建立在多的一方publish = models.ForeignKey(to="Publish", to_field="nid", on_delete=models.CASCADE)# 与Author表建立多对多的关系,ManyToManyField可以建在两个模型中的任意一个,自动创建第三张表authors = models.ManyToManyField(to='Author', )
templates
books.html
<!DOCTYPE html> <html lang="en"> <head><meta charset="UTF-8"><title>图书管理系统</title> </head> {% load staticfiles %} <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/css/bootstrap.min.css"integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous"> <body> <h1>添加书籍</h1> <div class="col-md-8 col-md-offset-2 " ><a class="btn btn-primary" href="{% url 'addbooks' %}"> 添加书籍</a><table class="table table_striped table-bordered table-hover"><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>{{ book.nid }}</td><td>{{ book.title }}</td><td>{{ book.price }}</td><td>{{ book.publish.name }}</td><td>{{ book.publishDate | date:'Y-m-d'}}</td><td>{% for auth in book.authors.all.values %}{% if forloop.last %}<span>{{ auth.name }} </span>{% else %}<span>{{ auth.name }} ,</span>{% endif %}{% endfor %}</td><td><a class=" btn btn-warning data-toggle='button" href="{% url 'editbooks' book.nid %}">编辑</a><a type="button" class="btn btn-danger data-toggle='button"href="{% url 'delete' book.nid %}">删除</a></td></tr>{% endfor %}</tbody></table> </div><script src="https://cdn.jsdelivr.net/npm/jquery@1.12.4/dist/jquery.min.js"></script> <!-- 加载 Bootstrap 的所有 JavaScript 插件。你也可以根据需要只加载单个插件。 --> <script src="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/js/bootstrap.min.js"></script> </body> </html>
addbooks.html
<!DOCTYPE html> <html lang="en"> <head><meta charset="UTF-8"><title>添加书籍</title> </head> {% load staticfiles %} <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/css/bootstrap.min.css"integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous"> <body> <h1>添加书籍</h1> <div class="col-md-8 col-md-offset-2 "><form class="form-horizontal" role="form" method="post" action="">{% csrf_token %}<div class="form-group"><label>书籍名称</label><input type="text" class="form-control" name="title" placeholder="书籍名称"></div><div class="form-group"><label>价格</label><input type="text" class="form-control" name="price" placeholder="价格"></div><div class="form-group"><label for="">出版社</label><select class="form-control" name="publish_id">{% for publish in publish_list %}<option value="{{ publish.pk }}">{{ publish.name }}</option>{% endfor %}</select></div><div class="form-group"><label>出版时间</label><input type="date" class="form-control" name="pub_date" placeholder="出版时间"></div><div class="form-group"><label for="">作者</label><select multiple class="form-control" name="author_id_list">{% for author in author_list %}<option value="{{ author.pk }}">{{ author.name }}</option>{% endfor %}</select></div><input class="btn btn-success data-toggle='button" formmethod="post" type="submit"></form> </div></body> </html>
editbooks.html
<!DOCTYPE html> <html lang="en"> <head><meta charset="UTF-8"><title>编辑书籍</title> </head> {% load staticfiles %} <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/css/bootstrap.min.css"integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous"> <body> <h1>编辑书籍</h1> <div class="col-md-8 col-md-offset-2 "><form class="form-horizontal" role="form" method="post" action="">{% csrf_token %}<div class="form-group"><label>书籍名称</label><input type="text" class="form-control" value="{{ book_nid_obj.title }}" name="title" placeholder="书籍名称"></div><div class="form-group"><label>价格</label><input type="text" class="form-control" value="{{ book_nid_obj.price }}" name="price" placeholder="价格"></div><div class="form-group"><label for="">出版社</label><select class="form-control" name="publish_id">{% for publish in publish_list %}<option value="{{ publish.pk }}">{{ publish.name }}</option>{% endfor %}</select></div><div class="form-group"><label>出版时间</label><input type="date" class="form-control" name="pub_date" value="{{ book_nid_obj.publishDate | date:'Y-m-d' }}"placeholder="出版时间"></div><div class="form-group"><label for="">作者</label><select multiple class="form-control" name="author_id_list">{% for author in author_list %}<option value="{{ author.pk }}">{{ author.name }}</option>{% endfor %}</select></div><input class="btn btn-success data-toggle='button" formmethod="post" type="submit"></form> </div> </body> </html>
页面效果
其他功能等我学会了再来
转载于:https://www.cnblogs.com/mjiu/p/9997480.html
Django(图书管理系统)相关推荐
- django图书管理系统:
目录 图书管理系统: day54 文件夹: settings.py: urls.py migrations文件夹 __ init __ models.py: views.py static文件夹 te ...
- python django图书管理系统_Python框架:Django写图书管理系统(LMS)
Django模版文件配置 文件路径 test_site -- test_site -- settings.py TEMPLATES = [ { 'BACKEND': 'django.template. ...
- 使用django创建一个单表查询的图书管理系统
使用django创建一个单表查询的图书管理系统 在settings.py文件中添加(用于连接mysql数据库) DATABASES = {'default': {'ENGINE': 'django.d ...
- Django(part39)--制作图书管理系统
学习笔记,仅供参考,有错必究 文章目录 制作图书管理系统 第一步 第二步 第三步 制作图书管理系统 我们基于上一个博客Django(part38)–制作登录界面的mywebsite_bookstore ...
- 系统业务逻辑书籍_Python框架:Django写图书管理系统(LMS)
今天我会带大家真正写一个Django项目,对于入门来说是有点难度的,因为逻辑比较复杂,但是真正的知识就是函数与面向对象,这也是培养用Django思维写项目的开始 Django文件配置 Django模版 ...
- Python框架:Django写图书管理系统(LMS)
今天我会带大家真正写一个Django项目,对于入门来说是有点难度的,因为逻辑比较复杂,但是真正的知识就是函数与面向对象,这也是培养用Django思维写项目的开始 Django文件配置 Django模版 ...
- python实现gui+mysql图书管理系统_用Python Django框架写一个图书管理系统LMS
今天我会带大家真正写一个Django项目,对于入门来说是有点难度的,因为逻辑比较复杂,但是真正的知识就是函数与面向对象,这也是培养用Django思维写项目的开始 Django文件配置 Django模版 ...
- Django教程 —— 初步完善图书管理系统
引言 在 Django模型设计 中我们只设计了一个BookInfo模型类,内容好单调,接下来我们初步完善一下BMSTes图书管理系统. 模型设计 我们写项目写东西的时候都要养成良好的习惯,不要一来就上 ...
- Django 第九课 【图书管理系统案例】
目标网络样式 1:创建项目 #1.1终端配好相关虚拟环境 workon [虚拟环境] #1.2配置相关库文件 pip install [库] #1.3打开pycharm软件,新建Django项目,选择 ...
- 基于docker搭建django的web图书管理系统
一.概要 本次将使用docker搭建一个基于django框架的图书管理系统,本次用到的技术包括: docker基本命令: 数据卷挂载: dockerfile编写: docker网络技术: django ...
最新文章
- CUDA error: device-side assert triggered Assertion t 」= 0 t n classes failed
- FreeRTOS 临界段和开关中断
- (转载)详解Hive配置Kerberos认证
- ubuntu14.0.4下安装pycharm
- linux环境下作业调度,Linux集群环境下作业调度算法的研究与实现
- mavenspringboot项目打包引入lib目录下jar包
- java 返回集合_java – List返回一个对象集合
- 青蛙学Linux—CentOS 6.10的安装
- 项目开发文档是必须的
- 学习|Android使用TTS语音合成
- emqx速度_速率限制
- RuntimeError: Cannot re-initialize CUDA in forked subprocess解决方法之一
- 27-如何让文件夹中的图片显示缩略图
- [日推荐] 『雅思口语自练狂』雅思考试神助攻!
- 武汉理工大学计算机考研考纲,2018年武汉理工大学825流体力学考试大纲
- 小学四年级计算机考试题,小学四年级信息技术试卷题库.doc
- ORA-20005: object statistics are locked (stattype = ALL)-转
- python实现键盘记录木马
- 让弹幕飞一会儿——腾讯视频弹幕(39W+)爬取实战
- selenium java安装运行
热门文章
- 通过bat批处理命令进行adb push批量拉取文件
- 中国软件欧美出口工程名单:金蝶等入选第一梯队
- 远程 桌面 上, root 用户切换到普通用户, sudo su cheng 到普通用户。这样就可以进行pip了
- TRW2000操作手册 整理
- 海蜘蛛软路由 linux,海蜘蛛网络科技官方网站 :: 做最好的中文软路由 :: 软件路由器 :: 软路由 :: 软件路由 :: RouterOs...
- 智能楼宇中的安防监控系统
- Ubuntu安装后要做的事
- 计算机音乐谱大全西游记,(完整word版)经典歌曲曲谱大全_流行歌曲简谱合集(70页)-原创力文档...
- 基于Cocos Studio和BMfont制作艺术字体
- qq密码终结者_密码或隐私的终结? 是你的电话