当前位置:   article > 正文

Django异步请求和后台管理实战

Django异步请求和后台管理实战

项目概述

  1. 项目实现Ajax异步请求局部刷新
  2. 使用XAdmin后台模板
  3. 提供图片上传接口
  4. 在明细页应用了富文本编辑器
  5. 在加载图书信息的时候使用LazyLoad(图片懒加载)
  1. # 环境
  2. asgiref==3.7.2
  3. crispy-bootstrap3==2024.1
  4. defusedxml==0.7.1
  5. diff-match-patch==20230430
  6. Django==3.2.25
  7. django-ckeditor==5.9.0
  8. django-crispy-forms==2.0
  9. django-formtools==2.1
  10. django-import-export==3.2.0
  11. django-js-asset==2.0.0
  12. django-reversion==5.0.12
  13. django-stdimage==3.2.0
  14. et-xmlfile==1.1.0
  15. future==0.15.2
  16. httplib2==0.9.2
  17. MarkupPy==1.14
  18. odfpy==1.4.1
  19. openpyxl==3.1.3
  20. Pillow==6.2.0
  21. progressbar2==4.2.0
  22. PyMySQL==1.1.1
  23. python-utils==3.5.2
  24. pytz==2024.1
  25. PyYAML==6.0.1
  26. six==1.10.0
  27. sqlparse==0.4.4
  28. tablib==3.4.0
  29. typing_extensions==4.7.1
  30. xlrd==2.0.1
  31. xlwt==1.3.0

 

项目初始化并添加xadmin

  • 创建项目 python manage.py startapp bookshop,并在配置文件中完成注册
  • 根目录新建apps文件夹存放刚创建出来的项目
  • 根目录新建extra_apps文件夹存放xadmin源码
  1. # 添加修改settings.py
  2. import os,sys
  3. sys.path.insert(0, os.path.join(BASE_DIR, 'apps'))
  4. sys.path.insert(0, os.path.join(BASE_DIR, 'extra_apps'))
  5. INSTALLED_APPS = [
  6. 'django.contrib.admin',
  7. 'django.contrib.auth',
  8. 'django.contrib.contenttypes',
  9. 'django.contrib.sessions',
  10. 'django.contrib.messages',
  11. 'django.contrib.staticfiles',
  12. 'bookshop',
  13. 'xadmin',
  14. 'crispy_forms',
  15. 'crispy_bootstrap3',
  16. ]
  • 配置文件中设置项目根目录并将文件夹设置为Sources Root格式

  • 新建数据库连接并完成连接配置

  1. # settings.py 添加mysql连接信息
  2. DATABASES = {
  3. 'default': {
  4. 'ENGINE': 'django.db.backends.mysql',
  5. 'NAME': 'django_bookshops',
  6. 'USER': '用户名',
  7. 'PASSWORD': '密码',
  8. 'HOST': 'ip',
  9. 'PORT': '端口'
  10. }
  11. }
  12. # 根目录下与settings.py同文件夹下__init__.py 添加如下信息
  13. import pymysql
  14. pymysql.install_as_MySQLdb()
  • 前端文件添加

apps文件夹下新建Python Package文件命名static,在static文件夹下新建css、images、js文件夹

  1. # settings.py 下添加访问静态文件路径
  2. STATIC_URL = '/static/'
  3. STATICFILES_DIRS = [
  4. os.path.join(BASE_DIR,'apps','static')
  5. ]

将准备好的前端文件放在指定文件夹中,目录结构如下

  1. # 修改 HTML 文件
  2. # 顶部添加
  3. {% load static %}
  4. # 引入静态文件
  5. <link href="{% static 'css/book.css' %}" rel="stylesheet">
  • url路由配置

apps文件夹下的bookshop项目中新建urls.py 文件,并在根目录下与settings.py文件同目录下的urls.py文件中添加引入外部 url配置

  1. # settings.py 同目录下 urls.py配置
  2. from django.contrib import admin
  3. from django.urls import path
  4. # 调用其他app下定义的 url
  5. from django.urls import include
  6. urlpatterns = [
  7. path('admin/', admin.site.urls),
  8. path('home/', include('bookshop.urls'))
  9. ]
  10. # ==============apps目录下urls.py================
  11. from django.urls import path
  12. from bookshop import views as bookshop_views
  13. urlpatterns = [
  14. # =========前端 url请求:返回页面============
  15. path('', bookshop_views.book, name='book'),
  16. ]
  • 准备数据库models类并插入数据
  1. # models.py
  2. from django.db import models
  3. # 引入stdimage的模块
  4. from stdimage.models import StdImageField # 字段类型
  5. from stdimage.utils import UploadToUUID # 生成文件名
  6. from ckeditor_uploader.fields import RichTextUploadingField
  7. # Create your models here.
  8. class BookType(models.Model): # 图书类别 -- 计算机,法律,外语,。。。。
  9. name = models.CharField(max_length=100, null=False, verbose_name='名称') # 类别编码
  10. class Meta:
  11. verbose_name = "图书类别"
  12. verbose_name_plural = "图书类别"
  13. def __str__(self):
  14. return "%s" % self.name
  15. class Press(models.Model): # 出版社
  16. id = models.CharField(primary_key=True, max_length=100, null=False, verbose_name='编号') # 编号
  17. name = models.CharField(max_length=100, null=False, verbose_name='名称') # 名称
  18. city = models.CharField(max_length=100, null=False, verbose_name='城市') # 城市
  19. tel = models.CharField(max_length=100, null=False, verbose_name='电话') # 电话
  20. email = models.CharField(max_length=100, null=False, verbose_name='邮箱') # 邮箱
  21. address = models.CharField(max_length=100, null=False, verbose_name='地址') # 地址
  22. class Meta:
  23. verbose_name = "出版社"
  24. verbose_name_plural = "出版社"
  25. def __str__(self):
  26. return ("出版社编号:%s\t出版社名称:%s\n" % (self.id,self.name))
  27. # return "%s" % self.name
  28. class Author(models.Model): # 作者
  29. gender_choices = (("男", '男'), ('女', '女'))
  30. id = models.CharField(primary_key=True, max_length=100, null=False, verbose_name='编号') # 编号
  31. name = models.CharField(max_length=100, null=False, verbose_name='姓名') # 姓名
  32. gender = models.CharField(max_length=100, choices=gender_choices, verbose_name='性别') # 性别
  33. city = models.CharField(max_length=100, null=False, verbose_name='城市') # 城市
  34. tel = models.CharField(max_length=100, null=False, verbose_name='电话') # 电话
  35. email = models.CharField(max_length=100, null=False, verbose_name='邮箱') # 邮箱
  36. address = models.CharField(max_length=100, null=False, verbose_name='地址') # 地址
  37. class Meta:
  38. verbose_name = "作者"
  39. verbose_name_plural = "作者"
  40. def __str__(self):
  41. return "%s\n" % self.name
  42. class Book(models.Model): # 图书
  43. id = models.CharField(primary_key=True, max_length=100, null=False, verbose_name='编号') # 编号,主键
  44. name = models.CharField(max_length=100, null=False, verbose_name='名称') # 名称
  45. barcode = models.CharField(max_length=100, null=False, verbose_name='条形码') # 条形码
  46. type = models.ForeignKey("BookType", on_delete=models.CASCADE, verbose_name='类别') # 类别
  47. press = models.ForeignKey("Press", on_delete=models.CASCADE, verbose_name='出版社') # 出版社
  48. author = models.ForeignKey("Author", on_delete=models.CASCADE, verbose_name='作者') # 作者
  49. price = models.FloatField(null=False, verbose_name='单价') # 价格
  50. difficulty = models.CharField(max_length=100,null=False, verbose_name='难易程度') # 难易程度: 0--入门 1--中级 2--高级
  51. publish_date = models.DateField(null=False, verbose_name='发行时间') # 发行时间
  52. storage_in_num = models.IntegerField(null=False, verbose_name='入库量') # 入库量
  53. storage_in_date = models.DateField(null=False, verbose_name='入库时间') # 入库时间
  54. inventory_num = models.IntegerField(null=False, verbose_name='库存量') # 库存量
  55. class Meta:
  56. verbose_name = "图书"
  57. verbose_name_plural = "图书"
  58. def __str__(self):
  59. return "%s" % self.name
  1. # 同步数据库信息
  2. python manage.py makemigrations
  3. python manage.py migrate

Ajax 异步请求 

Ajax 即“Asynchronous JavaScript And XML”(异步 JavaScript 和 XML),是指一种创建交互式网页应用的网页开发技术。

AJAX 最大的优点是在不重新加载整个页面的情况下,可以与服务器交换数据并更新部分网页内容

  • 准备图书类别的JSON数据 
  1. # ************定义views视图********
  2. from django.shortcuts import render
  3. from django.http import HttpResponse,JsonResponse
  4. from apps.bookshop.models import *
  5. # Create your views here.
  6. # =============前端代码:返回页面===========
  7. def book(request):
  8. return render(request,'book.html')
  9. # =============后端代码:从数据库中提取数据封装成json返回给前端===========
  10. # 获取所有的图书类别
  11. def get_booktype(request):
  12. obj_booktypes = BookType.objects.all().values()
  13. # Queryset无法直接转换成 Json,只有python基础的数据类型才可以,最外层的集合转换成列表
  14. booktypes = list(obj_booktypes)
  15. # 插入全部选项
  16. booktypes.insert(0,{"id":0,"name":"全部"})
  17. # 返回前端 json格式
  18. return JsonResponse({'type':booktypes})
  19. # **********定义url路由************
  20. from django.urls import path
  21. from bookshop import views as bookshop_views
  22. urlpatterns = [
  23. # =========前端 url请求:返回页面============
  24. path('', bookshop_views.book, name='book'),
  25. # =========后端 url请求:返回json数据========
  26. path('booktype/get/', bookshop_views.get_booktype, name='booktype'),
  27. ]

  • 将后端返回的数据展示在页面上
  1. # book.html
  2. {% load static %}
  3. <!DOCTYPE html>
  4. <html>
  5. <head>
  6. <meta charset="UTF-8">
  7. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  8. <meta http-equiv="X-UA-Compatible" content="ie=edge">
  9. <title>图书页面</title>
  10. <!-- 新 Bootstrap 核心 CSS 文件 -->
  11. <link href="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
  12. <!--index.css-->
  13. <link href="{% static 'css/book.css' %}" rel="stylesheet">
  14. <!-- jQuery文件。务必在bootstrap.min.js 之前引入 -->
  15. <script src="https://cdn.staticfile.org/jquery/2.1.1/jquery.min.js"></script>
  16. <!-- 最新的 Bootstrap 核心 JavaScript 文件 -->
  17. <script src="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script>
  18. <!-- jQuery中的Transtion -->
  19. <script src="https://cdn.bootcss.com/jquery.transit/0.9.12/jquery.transit.min.js"></script>
  20. <!--引入LazyLoad-->
  21. <script src="{% static 'js/jquery.lazyload.min.js' %}"></script>
  22. </head>
  23. <body>
  24. <div class="container-fiuled header">
  25. <div class="container">
  26. <img src="{% static 'images/book_logo.png' %}">
  27. </div>
  28. </div>
  29. <div class="container typefilter">
  30. <div class="row">
  31. <div class="col-lg-1">类别:</div>
  32. <div class="col-lg-11 booktypes">
  33. <!-- Ajax动态加载 -->
  34. </div>
  35. </div>
  36. </div>
  37. <div class="container otherfilter">
  38. <form class="form-inline">
  39. <div class="col-lg-2 col-lg-offset-1">
  40. <div class="form-group-sm">
  41. <label>价格: &nbsp;&nbsp;</label>
  42. <select class="form-control price">
  43. <option value="0" selected>所有</option>
  44. <option value="1">0-20元</option>
  45. <option value="2">20-30元</option>
  46. <option value="3">30-40元</option>
  47. <option value="4">40-50元</option>
  48. <option value="5">50-60元</option>
  49. <option value="6">60-70元</option>
  50. <option value="7">70元以上</option>
  51. </select>
  52. </div>
  53. </div>
  54. <div class="col-lg-2">
  55. <div class="form-group-sm">
  56. <label>难易程度: &nbsp;&nbsp;</label>
  57. <select class="form-control difficulty">
  58. <option value="0" selected>所有</option>
  59. <option value="1">入门</option>
  60. <option value="2">中级</option>
  61. <option value="3">高级</option>
  62. </select>
  63. </div>
  64. </div>
  65. <div class="col-lg-2">
  66. <div class="form-group-sm">
  67. <span style="font-weight: bold">价格排序: </span>
  68. <span class="glyphicon glyphicon-sort-by-attributes asc" style="margin-left: 10px;"></span>
  69. <span class="glyphicon glyphicon-sort-by-attributes-alt desc" style="margin-left: 10px;"></span>
  70. </div>
  71. </div>
  72. <div class="col-lg-5" style="text-align: right">
  73. <div class="form-group-sm">
  74. <input type="text" class="form-control querystr" placeholder="输入图书关键字" style="width:360px;">
  75. <button class="btn btn-primary btn-sm btnquery" type="button">查找</button>
  76. </div>
  77. </div>
  78. </form>
  79. </div>
  80. <div class="container books" style="width:1220px;height: 400px;margin:20px auto;">
  81. <!-- Ajax动态加载 -->
  82. </div>
  83. </body>
  84. </html>
  1. #  JavaScript代码
  2. <script>
  3. // 入口函数
  4. $(document).ready(function (){
  5. // 代码自动执行(页面加载时自动执行)
  6. $.ajax({
  7. url: 'booktype/get/',
  8. method: 'GET',
  9. success: function (res){
  10. console.log(res)
  11. // 调用函数
  12. addTypes(res.type)
  13. }
  14. });
  15. });
  16. // DOM 操作
  17. // 将图书类别加载到指定区域
  18. function addTypes(types){
  19. // 清空指定区域内容
  20. $('.typefilter .booktypes').html("");
  21. // 循环加载图书类别
  22. types.forEach(function (element,index,array){
  23. // 新建一个 span
  24. let oneType = $('<span>').html(element.name).attr('value',element.id).css('font-size',"14px").css('font-weight','normal').css('margin',"10px");;
  25. //添加一个Hover操作
  26. oneType.on('mouseenter',()=>{
  27. oneType.css('font-weight','bold');
  28. }).on('mouseleave',()=>{
  29. oneType.css('font-weight','normal');
  30. });
  31. // 判断是不是全部
  32. if (index===0){
  33. oneType.css({'color':'red'});
  34. }
  35. // 添加到页面类别中
  36. oneType.appendTo($('.typefilter .booktypes'));
  37. });
  38. }
  39. </script>
  • 准备图书列表数据
  1. # ************定义views视图********
  2. from django.shortcuts import render
  3. from django.http import HttpResponse,JsonResponse
  4. from apps.bookshop.models import *
  5. # Create your views here.
  6. # =============前端代码:返回页面===========
  7. def book(request):
  8. return render(request,'book.html')
  9. # =============后端代码:从数据库中提取数据封装成json返回给前端===========
  10. # 获取所有的图书类别
  11. def get_booktype(request):
  12. obj_booktypes = BookType.objects.all().values()
  13. # Queryset无法直接转换成 Json,只有python基础的数据类型才可以,最外层的集合转换成列表
  14. booktypes = list(obj_booktypes)
  15. # 插入全部选项
  16. booktypes.insert(0,{"id":0,"name":"全部"})
  17. # 返回前端 json格式
  18. return JsonResponse({'type':booktypes})
  19. # 获取所有的图书列表
  20. def get_books(request):
  21. obj_books = Book.objects.all().values()
  22. # Queryset无法直接转换成 Json,只有python基础的数据类型才可以,最外层的集合转换成列表
  23. books = list(obj_books)
  24. # 遍历图书 获取类别名称
  25. for index,item in enumerate(books):
  26. # 根据类别编号获取图书类别的对象
  27. obj_type = BookType.objects.get(id=item['type_id'])
  28. # 附加typename到当前成员
  29. books[index]['typename'] = obj_type.name
  30. # 返回前端 json格式
  31. # return JsonResponse({'book': books})
  32. # 'ensure_ascii': False 返回的数据显示中文
  33. return JsonResponse({'book': books},json_dumps_params={'ensure_ascii': False})
  34. # **********定义url路由************
  35. from django.urls import path
  36. from bookshop import views as bookshop_views
  37. urlpatterns = [
  38. # =========前端 url请求:返回页面============
  39. path('', bookshop_views.book, name='book'),
  40. # =========后端 url请求:返回json数据========
  41. path('booktype/get/', bookshop_views.get_booktype, name='booktype'),
  42. path('books/get/', bookshop_views.get_books, name='books'),
  43. ]

  • 将后端返回的图书展示在页面上
  1. #  JavaScript代码
  2. <script>
  3. // 入口函数
  4. $(document).ready(function (){
  5. // 代码自动执行(页面加载时自动执行)
  6. $.ajax({
  7. url: 'booktype/get/',
  8. method: 'GET',
  9. success: function (res){
  10. console.log(res)
  11. // 调用函数
  12. addTypes(res.type)
  13. }
  14. });
  15. // *******自动加载图书列表(页面加载时自动执行)*******
  16. $.ajax({
  17. url: 'books/get/',
  18. method: 'GET',
  19. success: function (res){
  20. console.log(res)
  21. // 调用函数
  22. addBooks(res.book)
  23. }
  24. });
  25. });
  26. // DOM 操作
  27. // 将图书类别加载到指定区域
  28. function addTypes(types){
  29. // 清空指定区域内容
  30. $('.typefilter .booktypes').html("");
  31. // 循环加载图书类别
  32. types.forEach(function (element,index,array){
  33. // 新建一个 span
  34. let oneType = $('<span>').html(element.name).attr('value',element.id).css('font-size',"14px").css('font-weight','normal').css('margin',"10px");;
  35. //添加一个Hover操作
  36. oneType.on('mouseenter',()=>{
  37. oneType.css('font-weight','bold');
  38. }).on('mouseleave',()=>{
  39. oneType.css('font-weight','normal');
  40. });
  41. // 判断是不是全部
  42. if (index===0){
  43. oneType.css({'color':'red'});
  44. }
  45. // 添加到页面类别中
  46. oneType.appendTo($('.typefilter .booktypes'));
  47. });
  48. }
  49. //**********把图书列表加载到制定区域*********
  50. function addBooks(books) {
  51. //清空区域内容
  52. $('.books').html("");
  53. //遍历
  54. books.forEach(function (element, index, array) {
  55. //新建一个div-最外层的容器
  56. let outer = $('<div>').attr( "class", "col-lg-3");
  57. //新建一个div,设置类为thumbnail
  58. let thumbnail = $('<div>').attr( "class", "thumbnail").css('overflow','hidden').appendTo(outer);
  59. //新建一个img标签,放置图片
  60. let img = $('<img>')
  61. .attr('scr',baseURL+element.image) //******
  62. .appendTo(thumbnail)
  63. //设置图的hover过渡特效 --- 放大1.4倍
  64. img.on('mouseenter',function () {
  65. img.transition({ scale: 1.4 }, 300);
  66. }).on('mouseleave',function () {
  67. img.transition({ scale: 1 }, 300);
  68. });
  69. //新建一个div--放置价格
  70. let price = $('<div>').html("价格:" + element.price.toFixed(2) + "元").css('text-align', 'left').css('color','red').css('margin-top','20px').css('font-size','16px')
  71. .css('line-height', '30px').appendTo(thumbnail);
  72. {#$("<span>").html("类别:" + element.typename).css('text-align', 'left').css('font-size','16px')#}
  73. {# .css('line-height', '30px').appendTo(thumbnail);#}
  74. //新建一个div--放置图书名称
  75. let bookname =$('<div>').html(element.name).css('text-align', 'left').css('color','navy').css('font-size','16px').appendTo(thumbnail);
  76. //设置图书名称的 Hover
  77. bookname.on('mouseenter',function () {
  78. bookname.css('font-weight','bold');
  79. }).on('mouseleave',function () {
  80. bookname.css('font-weight','normal');
  81. });
  82. //把当前容器放置在页面上
  83. outer.appendTo($('.books'))
  84. });
  85. }
  86. </script>
  • 效果如下 

xadmin 部署及配置

  • 引入源码到项目中
  1. # 安装xadmin的依赖包进入源码的目录
  2. pip install -r requirements.txt
  • 安装核心的包
  1. INSTALLED_APPS = [
  2. 'django.contrib.admin',
  3. 'django.contrib.auth',
  4. 'django.contrib.contenttypes',
  5. 'django.contrib.sessions',
  6. 'django.contrib.messages',
  7. 'django.contrib.staticfiles',
  8. 'bookshop',
  9. 'xadmin',
  10. 'crispy_forms',
  11. 'crispy_bootstrap3',
  12. ]
  • 修改URL
  1. from django.contrib import admin
  2. from django.urls import path
  3. # 调用其他app下定义的 url
  4. from django.urls import include
  5. # 引入 xadmin
  6. import xadmin
  7. urlpatterns = [
  8. # path('admin/', admin.site.urls),
  9. path('xadmin/', xadmin.site.urls),
  10. path('home/', include('bookshop.urls'))
  11. ]
  • 同步数据库
  1. python manage.py makemigrations
  2. python manage.py migrate
  • 设置管理员账号密码
python manage.py createsuperuser
  • 报错问题解决
  1. 解决报错 render() missing 1 required positional argument: 'form_style'
  2. 1.utils.py 29行render_field()中添加form_style=None,
  3. 2.删除 detail.py 3435行form_style
  4. 解决报错 render() missing 1 required positional argument: context
  5. 1.utils.py 66行context变为context=context
  6. 解决报错 OperationalError: (1271, "Illegal mix of collations for operation 'like'")
  7. 1.找到django包下面的\site-packages\django\db\backends\mysql\base.py文件,编辑
  8. 将icontains的值 'icontains': 'LIKE %s',改为'icontains': 'LIKE BINARY %s',
  9. 解决报错 django.template.exceptions.TemplateDoesNotExist: bootstrap3/errors.html
  10. 1.安装 pip install crispy-bootstrap3 -i https://mirrors.aliyun.com/pypi/simple/
  11. 2.注册 'crispy_bootstrap3'
  • Models类注册到xadmin
  1. # 1.后台界面中文显示,更改 settings.py
  2. # 语言
  3. # LANGUAGE_CODE = 'en-us'
  4. LANGUAGE_CODE = 'zh-Hans'
  5. # 时区
  6. # TIME_ZONE = 'UTC'
  7. TIME_ZONE = 'Asia/Shanghai'
  8. # 2.bookshop目录下新建 adminx.py 文件
  9. from apps.bookshop import models
  10. import xadmin
  11. # 定义相应对象的xadmin类
  12. class PressAdmin(object):
  13. # 配置表格显示字段
  14. list_display = ['id','name','city','tel','email','address']
  15. # 分页
  16. list_per_page = 10
  17. # 将类注册到xadmin
  18. xadmin.site.register(models.Press,PressAdmin)
  19. # 定义相应对象的xadmin类
  20. class BookTypeAdmin(object):
  21. # 配置表格显示字段
  22. list_display = ['name']
  23. # 分页
  24. list_per_page = 10
  25. # 将类注册到xadmin
  26. xadmin.site.register(models.BookType,BookTypeAdmin)
  27. # 定义相应对象的xadmin类
  28. class AuthorAdmin(object):
  29. # 配置表格显示字段
  30. list_display = ['id','name','city','gender','tel','email','address']
  31. # 分页
  32. list_per_page = 10
  33. # 将类注册到xadmin
  34. xadmin.site.register(models.Author,AuthorAdmin)
  35. # 定义相应对象的xadmin类
  36. class BookAdmin(object):
  37. # 配置表格显示字段
  38. list_display = ['id','name','barcode','type','press','author','price','difficulty','publish_date','storage_in_num','storage_in_date','inventory_num']
  39. # 分页
  40. list_per_page = 10
  41. # 排序
  42. ordering = ['id']
  43. # 查看详情
  44. show_detail_fields = ['id']
  45. # 图标 https://v3.bootcss.com/components/
  46. # https://fontawesome.com/v4/icons/
  47. model_icon = "fa fa-signal"
  48. # 搜索字段
  49. search_fields = ['id','name','barcode']
  50. # 筛选字段
  51. list_filter = ['id','name','barcode','type','press','author','price']
  52. # 配置自动刷新的时间
  53. refresh_times = (3,5)
  54. # 将类注册到xadmin
  55. xadmin.site.register(models.Book,BookAdmin)
  • xadmin中全局配置
  1. from apps.bookshop import models
  2. import xadmin
  3. # 定义相应对象的xadmin类
  4. class PressAdmin(object):
  5. # 配置表格显示字段
  6. list_display = ['id','name','city','tel','email','address']
  7. # 分页
  8. list_per_page = 10
  9. # 将类注册到xadmin
  10. xadmin.site.register(models.Press,PressAdmin)
  11. # 定义相应对象的xadmin类
  12. class BookTypeAdmin(object):
  13. # 配置表格显示字段
  14. list_display = ['name']
  15. # 分页
  16. list_per_page = 10
  17. # 将类注册到xadmin
  18. xadmin.site.register(models.BookType,BookTypeAdmin)
  19. # 定义相应对象的xadmin类
  20. class AuthorAdmin(object):
  21. # 配置表格显示字段
  22. list_display = ['id','name','city','gender','tel','email','address']
  23. # 分页
  24. list_per_page = 10
  25. # 将类注册到xadmin
  26. xadmin.site.register(models.Author,AuthorAdmin)
  27. # 定义相应对象的xadmin类
  28. class BookAdmin(object):
  29. # 配置表格显示字段
  30. list_display = ['id','name','barcode','type','press','author','price','difficulty','publish_date','storage_in_num','storage_in_date','inventory_num']
  31. # 分页
  32. list_per_page = 10
  33. # 排序
  34. ordering = ['id']
  35. # 查看详情
  36. show_detail_fields = ['id']
  37. # 图标 https://v3.bootcss.com/components/
  38. # https://fontawesome.com/v4/icons/
  39. model_icon = "fa fa-signal"
  40. # 搜索字段
  41. search_fields = ['id','name','barcode']
  42. # 筛选字段
  43. list_filter = ['id','name','barcode','type','press','author','price']
  44. # 配置自动刷新的时间
  45. refresh_times = (3,5)
  46. # 将类注册到xadmin
  47. xadmin.site.register(models.Book,BookAdmin)
  48. """========修改全局基础配置=========="""
  49. from xadmin import views
  50. class BaseSetting(object):
  51. # 是否启用主题
  52. enable_themes = True
  53. use_bootswatch = True
  54. def has_add_permission(self,request):
  55. return False
  56. class GlobalSetting(object):
  57. site_title = '后台管理系统'
  58. site_footer = '版权所有 @lv'
  59. # 侧边栏收起
  60. menu_style = 'accordion'
  61. # *****将全局配置配置到xadmin中*****
  62. xadmin.site.register(views.BaseAdminView,BaseSetting)
  63. xadmin.site.register(views.CommAdminView,GlobalSetting)

图片上传功能实现

  • 准备存储图片的文件夹media
  • 设置MEDIA ROOT 和 MEDIA URL
  1. # MEDIA ROOT:本地处理的路径,MEDIA URL: 互联网访问的路径
  2. # settings.py
  3. MEDIA_ROOT = os.path.join(BASE_DIR,'media')
  4. MEDIA_URL = ''
  • 配置URL
  1. from django.urls import path
  2. # 调用其他app下定义的 url
  3. from django.urls import include
  4. # 引入 xadmin
  5. import xadmin
  6. from django.conf import settings
  7. # 匹配静态文件
  8. from django.conf.urls.static import static
  9. urlpatterns = [
  10. # path('admin/', admin.site.urls),
  11. path('xadmin/', xadmin.site.urls),
  12. path('home/', include('bookshop.urls'))
  13. ]
  14. # 允许所有的图片被访问
  15. urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
  • 安装模块
pip install django-stdimage==3.2.0 -i https://mirrors.aliyun.com/pypi/simple/
  • 配置models.py模版文件
  1. # 引入stdimage的模块
  2. from stdimage.models import StdImageField
  3. # 生成唯一文件名
  4. from stdimage.utils import UploadToUUID
  5. # 添加图书字段
  6. # path="" 默认存储到media下 variations缩略图配置
  7. image = StdImageField(max_length=200, upload_to=UploadToUUID(path=""),
  8. verbose_name='图片', variations={'thumbnail': {'width': 70, 'height': 100}})
  •  更新连接表
python manage.py makemigrations
  • 实现上传的图片在前台显示
  1. #  JavaScript代码
  2. <script>
  3. // 入口函数
  4. $(document).ready(function (){
  5. // 代码自动执行(页面加载时自动执行)
  6. $.ajax({
  7. url: 'booktype/get/',
  8. method: 'GET',
  9. success: function (res){
  10. console.log(res)
  11. // 调用函数
  12. addTypes(res.type)
  13. }
  14. });
  15. // *******自动加载图书列表(页面加载时自动执行)*******
  16. $.ajax({
  17. url: 'books/get/',
  18. method: 'GET',
  19. success: function (res){
  20. console.log(res)
  21. // 调用函数
  22. addBooks(res.book)
  23. }
  24. });
  25. });
  26. // DOM 操作
  27. // 将图书类别加载到指定区域
  28. function addTypes(types){
  29. // 清空指定区域内容
  30. $('.typefilter .booktypes').html("");
  31. // 循环加载图书类别
  32. types.forEach(function (element,index,array){
  33. // 新建一个 span
  34. let oneType = $('<span>').html(element.name).attr('value',element.id).css('font-size',"14px").css('font-weight','normal').css('margin',"10px");;
  35. //添加一个Hover操作
  36. oneType.on('mouseenter',()=>{
  37. oneType.css('font-weight','bold');
  38. }).on('mouseleave',()=>{
  39. oneType.css('font-weight','normal');
  40. });
  41. // 判断是不是全部
  42. if (index===0){
  43. oneType.css({'color':'red'});
  44. }
  45. // 添加到页面类别中
  46. oneType.appendTo($('.typefilter .booktypes'));
  47. });
  48. }
  49. //**********把图书列表加载到制定区域*********
  50. function addBooks(books) {
  51. //清空区域内容
  52. $('.books').html("");
  53. //*********定义一个基础的URL********
  54. let baseURL = "http://127.0.0.1:8000/";
  55. //遍历
  56. books.forEach(function (element, index, array) {
  57. //新建一个div-最外层的容器
  58. let outer = $('<div>').attr( "class", "col-lg-3");
  59. //新建一个div,设置类为thumbnail
  60. let thumbnail = $('<div>').attr( "class", "thumbnail").css('overflow','hidden').appendTo(outer);
  61. //新建一个img标签,放置图片
  62. let img = $('<img>')
  63. .attr('scr',baseURL+element.image) //******
  64. .appendTo(thumbnail)
  65. //设置图的hover过渡特效 --- 放大1.4倍
  66. img.on('mouseenter',function () {
  67. img.transition({ scale: 1.4 }, 300);
  68. }).on('mouseleave',function () {
  69. img.transition({ scale: 1 }, 300);
  70. });
  71. //新建一个div--放置价格
  72. let price = $('<div>').html("价格:" + element.price.toFixed(2) + "元").css('text-align', 'left').css('color','red').css('margin-top','20px').css('font-size','16px')
  73. .css('line-height', '30px').appendTo(thumbnail);
  74. {#$("<span>").html("类别:" + element.typename).css('text-align', 'left').css('font-size','16px')#}
  75. {# .css('line-height', '30px').appendTo(thumbnail);#}
  76. //新建一个div--放置图书名称
  77. let bookname =$('<div>').html(element.name).css('text-align', 'left').css('color','navy').css('font-size','16px').appendTo(thumbnail);
  78. //设置图书名称的 Hover
  79. bookname.on('mouseenter',function () {
  80. bookname.css('font-weight','bold');
  81. }).on('mouseleave',function () {
  82. bookname.css('font-weight','normal');
  83. });
  84. //把当前容器放置在页面上
  85. outer.appendTo($('.books'))
  86. });
  87. }
  88. </script>

 

图书筛选功能实现

  • 图书类别筛选
  1. #  前端JavaScript代码
  2. <script>
  3. // *******
  4. queryItems = {
  5. type: 0, //类别
  6. pricemin: 0, //价格区间的最小值
  7. pricemax: 10000,//价格区间的最大值
  8. difficulty: "0", //难易程度
  9. order: 0, //排序: 0-不排序 1-升序 2-降序
  10. inputstr: "", //输入的查询字符串
  11. };
  12. // 入口函数
  13. $(document).ready(function (){
  14. // 代码自动执行(页面加载时自动执行)
  15. $.ajax({
  16. url: 'booktype/get/',
  17. method: 'GET',
  18. success: function (res){
  19. console.log(res)
  20. // 调用函数展示筛选后的图书
  21. addTypes(res.type)
  22. }
  23. });
  24. // *******自动加载图书列表(页面加载时自动执行)*******
  25. $.ajax({
  26. url: 'books/get/',
  27. method: 'GET',
  28. success: function (res){
  29. console.log(res)
  30. // 调用函数
  31. addBooks(res.book)
  32. }
  33. });
  34. });
  35. // DOM 操作
  36. // 提交图书查询的ajax请求
  37. function queryBooks(){
  38. // 进行ajax请求
  39. $.ajax({
  40. url: "books/query/",
  41. method: "post",
  42. data: queryItems,
  43. success:function (res){
  44. console.log(res);
  45. // 展示筛选后的图书
  46. addBooks(res.book)
  47. }
  48. })
  49. }
  50. // 将图书类别加载到指定区域
  51. function addTypes(types){
  52. // 清空指定区域内容
  53. $('.typefilter .booktypes').html("");
  54. // 循环加载图书类别
  55. types.forEach(function (element,index,array){
  56. // 新建一个 span
  57. let oneType = $('<span>').html(element.name).attr('value',element.id).css('font-size',"14px").css('font-weight','normal').css('margin',"10px");;
  58. //添加一个Hover操作
  59. oneType.on('mouseenter',()=>{
  60. oneType.css('font-weight','bold');
  61. }).on('mouseleave',()=>{
  62. oneType.css('font-weight','normal');
  63. });
  64. // 判断是不是全部
  65. if (index===0){
  66. oneType.css({'color':'red'});
  67. }
  68. // *****响应事件*****
  69. // 类别点击事件
  70. oneType.click(function (){
  71. //清楚所有的选择
  72. $(".booktypes span").css('color','#000');
  73. //把点击的选择
  74. $(this).css('color','red');
  75. // 把typeid传递给 queryitme.type
  76. queryItems.type = $(this).attr('value');
  77. {#console.log(queryItems);#}
  78. //提交到后台筛选
  79. queryBooks()
  80. // 添加到页面类别中
  81. oneType.appendTo($('.typefilter .booktypes'));
  82. });
  83. }
  84. //**********把图书列表加载到制定区域*********
  85. function addBooks(books) {
  86. //清空区域内容
  87. $('.books').html("");
  88. //*********定义一个基础的URL********
  89. let baseURL = "http://127.0.0.1:8000/";
  90. //遍历
  91. books.forEach(function (element, index, array) {
  92. //新建一个div-最外层的容器
  93. let outer = $('<div>').attr( "class", "col-lg-3");
  94. //新建一个div,设置类为thumbnail
  95. let thumbnail = $('<div>').attr( "class", "thumbnail").css('overflow','hidden').appendTo(outer);
  96. //新建一个img标签,放置图片
  97. let img = $('<img>')
  98. .attr('scr',baseURL+element.image) //******
  99. .appendTo(thumbnail)
  100. //设置图的hover过渡特效 --- 放大1.4倍
  101. img.on('mouseenter',function () {
  102. img.transition({ scale: 1.4 }, 300);
  103. }).on('mouseleave',function () {
  104. img.transition({ scale: 1 }, 300);
  105. });
  106. //新建一个div--放置价格
  107. let price = $('<div>').html("价格:" + element.price.toFixed(2) + "元").css('text-align', 'left').css('color','red').css('margin-top','20px').css('font-size','16px')
  108. .css('line-height', '30px').appendTo(thumbnail);
  109. {#$("<span>").html("类别:" + element.typename).css('text-align', 'left').css('font-size','16px')#}
  110. {# .css('line-height', '30px').appendTo(thumbnail);#}
  111. //新建一个div--放置图书名称
  112. let bookname =$('<div>').html(element.name).css('text-align', 'left').css('color','navy').css('font-size','16px').appendTo(thumbnail);
  113. //设置图书名称的 Hover
  114. bookname.on('mouseenter',function () {
  115. bookname.css('font-weight','bold');
  116. }).on('mouseleave',function () {
  117. bookname.css('font-weight','normal');
  118. });
  119. //把当前容器放置在页面上
  120. outer.appendTo($('.books'))
  121. });
  122. }
  123. </script>
  1. # 后端代码 view.py
  2. from django.shortcuts import render
  3. from django.http import HttpResponse,JsonResponse
  4. from apps.bookshop.models import *
  5. # 实现图书查询
  6. def query_books(request):
  7. # 获取传递来的条件
  8. type = request.POST.get('type')
  9. if type == '0':
  10. obj_books = Book.objects.all().values()
  11. else:
  12. # 通过编号筛选出图书
  13. obj_books = Book.objects.filter(type_id=type).values()
  14. books = list(obj_books.values())
  15. # 遍历图书 获取类别名称
  16. for index, item in enumerate(books):
  17. # 根据类别编号获取图书类别的对象
  18. obj_type = BookType.objects.get(id=item['type_id'])
  19. # 附加typename到当前成员
  20. books[index]['typename'] = obj_type.name
  21. return JsonResponse({'book': books}, json_dumps_params={'ensure_ascii': False})
  22. # 设置路由 urls.py
  23. from django.urls import path
  24. from bookshop import views as bookshop_views
  25. urlpatterns = [
  26. # =========前端 url请求:返回页面============
  27. path('', bookshop_views.book, name='book'),
  28. # =========后端 url请求:返回json数据========
  29. path('booktype/get/', bookshop_views.get_booktype, name='booktype'),
  30. path('books/get/', bookshop_views.get_books, name='books'),
  31. path('books/query/', bookshop_views.query_books, name='books_query'),
  32. ]
  • 图书价格区间筛选
  1. #  前端JavaScript代码
  2. <script>
  3. // *******
  4. PRICE_REGION_VALUE = [[0,10000],[0,20],[20,30],[30,40],[40,50],[50,60],[60,70],[70,10000]];
  5. DIFF_VALUE =['0', '入门', '中级', '高级'];
  6. queryItems = {
  7. type: 0, //类别
  8. pricemin: 0, //价格区间的最小值
  9. pricemax: 10000,//价格区间的最大值
  10. difficulty: "0", //难易程度
  11. order: 0, //排序: 0-不排序 1-升序 2-降序
  12. inputstr: "", //输入的查询字符串
  13. };
  14. // 入口函数
  15. $(document).ready(function (){
  16. // 代码自动执行(页面加载时自动执行)
  17. $.ajax({
  18. url: 'booktype/get/',
  19. method: 'GET',
  20. success: function (res){
  21. console.log(res)
  22. // 调用函数展示筛选后的图书
  23. addTypes(res.type)
  24. }
  25. });
  26. // *******自动加载图书列表(页面加载时自动执行)*******
  27. $.ajax({
  28. url: 'books/get/',
  29. method: 'GET',
  30. success: function (res){
  31. console.log(res)
  32. // 调用函数
  33. addBooks(res.book)
  34. }
  35. });
  36. // *******价格的下拉框改变事件*******
  37. $('.price').change(function (){
  38. let priceArr = PRICE_REGION_VALUE[parseInt($('.price').val())];
  39. // 范围值赋值给pricemin、pricemax
  40. queryItems.pricemin = priceArr[0];
  41. queryItems.pricemax = priceArr[1];
  42. // 传递到后端
  43. queryBooks()
  44. });
  45. });
  46. // DOM 操作
  47. // 提交图书查询的ajax请求
  48. function queryBooks(){
  49. // 进行ajax请求
  50. $.ajax({
  51. url: "books/query/",
  52. method: "post",
  53. data: queryItems,
  54. success:function (res){
  55. console.log(res);
  56. // 展示筛选后的图书
  57. addBooks(res.book)
  58. }
  59. })
  60. }
  61. // 将图书类别加载到指定区域
  62. function addTypes(types){
  63. // 清空指定区域内容
  64. $('.typefilter .booktypes').html("");
  65. // 循环加载图书类别
  66. types.forEach(function (element,index,array){
  67. // 新建一个 span
  68. let oneType = $('<span>').html(element.name).attr('value',element.id).css('font-size',"14px").css('font-weight','normal').css('margin',"10px");;
  69. //添加一个Hover操作
  70. oneType.on('mouseenter',()=>{
  71. oneType.css('font-weight','bold');
  72. }).on('mouseleave',()=>{
  73. oneType.css('font-weight','normal');
  74. });
  75. // 判断是不是全部
  76. if (index===0){
  77. oneType.css({'color':'red'});
  78. }
  79. // *****响应事件*****
  80. // 类别点击事件
  81. oneType.click(function (){
  82. //清楚所有的选择
  83. $(".booktypes span").css('color','#000');
  84. //把点击的选择
  85. $(this).css('color','red');
  86. // 把typeid传递给 queryitme.type
  87. queryItems.type = $(this).attr('value');
  88. {#console.log(queryItems);#}
  89. //提交到后台筛选
  90. queryBooks()
  91. // 添加到页面类别中
  92. oneType.appendTo($('.typefilter .booktypes'));
  93. });
  94. }
  95. //**********把图书列表加载到制定区域*********
  96. function addBooks(books) {
  97. //清空区域内容
  98. $('.books').html("");
  99. //*********定义一个基础的URL********
  100. let baseURL = "http://127.0.0.1:8000/";
  101. //遍历
  102. books.forEach(function (element, index, array) {
  103. //新建一个div-最外层的容器
  104. let outer = $('<div>').attr( "class", "col-lg-3");
  105. //新建一个div,设置类为thumbnail
  106. let thumbnail = $('<div>').attr( "class", "thumbnail").css('overflow','hidden').appendTo(outer);
  107. //新建一个img标签,放置图片
  108. let img = $('<img>')
  109. .attr('scr',baseURL+element.image) //******
  110. .appendTo(thumbnail)
  111. //设置图的hover过渡特效 --- 放大1.4倍
  112. img.on('mouseenter',function () {
  113. img.transition({ scale: 1.4 }, 300);
  114. }).on('mouseleave',function () {
  115. img.transition({ scale: 1 }, 300);
  116. });
  117. //新建一个div--放置价格
  118. let price = $('<div>').html("价格:" + element.price.toFixed(2) + "元").css('text-align', 'left').css('color','red').css('margin-top','20px').css('font-size','16px')
  119. .css('line-height', '30px').appendTo(thumbnail);
  120. {#$("<span>").html("类别:" + element.typename).css('text-align', 'left').css('font-size','16px')#}
  121. {# .css('line-height', '30px').appendTo(thumbnail);#}
  122. //新建一个div--放置图书名称
  123. let bookname =$('<div>').html(element.name).css('text-align', 'left').css('color','navy').css('font-size','16px').appendTo(thumbnail);
  124. //设置图书名称的 Hover
  125. bookname.on('mouseenter',function () {
  126. bookname.css('font-weight','bold');
  127. }).on('mouseleave',function () {
  128. bookname.css('font-weight','normal');
  129. });
  130. //把当前容器放置在页面上
  131. outer.appendTo($('.books'))
  132. });
  133. }
  134. </script>
  1. # 后端代码 view.py
  2. from django.shortcuts import render
  3. from django.http import HttpResponse,JsonResponse
  4. from apps.bookshop.models import *
  5. # 实现图书查询
  6. def query_books(request):
  7. # 获取传递来的条件
  8. type = request.POST.get('type')
  9. # 价格
  10. price_min = request.POST.get('pricemin')
  11. price_max = request.POST.get('pricemax')
  12. if type == '0':
  13. obj_books = Book.objects.all().values()
  14. else:
  15. # 通过编号筛选出图书
  16. obj_books = Book.objects.filter(type_id=type).values()
  17. # 筛选价格
  18. obj_books = obj_books.filter(price__gte=price_min,price__lte=price_max)
  19. books = list(obj_books.values())
  20. # 遍历图书 获取类别名称
  21. for index, item in enumerate(books):
  22. # 根据类别编号获取图书类别的对象
  23. obj_type = BookType.objects.get(id=item['type_id'])
  24. # 附加typename到当前成员
  25. books[index]['typename'] = obj_type.name
  26. return JsonResponse({'book': books}, json_dumps_params={'ensure_ascii': False})
  27. # 设置路由 urls.py
  28. from django.urls import path
  29. from bookshop import views as bookshop_views
  30. urlpatterns = [
  31. # =========前端 url请求:返回页面============
  32. path('', bookshop_views.book, name='book'),
  33. # =========后端 url请求:返回json数据========
  34. path('booktype/get/', bookshop_views.get_booktype, name='booktype'),
  35. path('books/get/', bookshop_views.get_books, name='books'),
  36. path('books/query/', bookshop_views.query_books, name='books_query'),
  37. ]

 

  • 图书难易程度筛选
  1. # 前端 JavaScript代码
  2. // 入口函数添加 难度筛选事件
  3. $('.difficulty').change(function (){
  4. queryItems.difficulty = DIFF_VALUE[parseInt($('.difficulty').val())]
  5. // 实现查询
  6. queryBooks();
  7. });
  8. # 后端图书查询函数添加
  9. # 实现图书查询
  10. def query_books(request):
  11. # 获取传递来的条件
  12. type = request.POST.get('type')
  13. # 价格
  14. price_min = request.POST.get('pricemin')
  15. price_max = request.POST.get('pricemax')
  16. # 难度
  17. difficulty = request.POST.get('difficulty')
  18. if type == '0':
  19. obj_books = Book.objects.all().values()
  20. else:
  21. # 通过编号筛选出图书
  22. obj_books = Book.objects.filter(type_id=type).values()
  23. # 筛选价格
  24. obj_books = obj_books.filter(price__gte=price_min,price__lte=price_max)
  25. # 筛选难度
  26. if '0' not in difficulty:
  27. obj_books = obj_books.filter(difficulty=difficulty)
  28. books = list(obj_books.values())
  29. # 遍历图书 获取类别名称
  30. for index, item in enumerate(books):
  31. # 根据类别编号获取图书类别的对象
  32. obj_type = BookType.objects.get(id=item['type_id'])
  33. # 附加typename到当前成员
  34. books[index]['typename'] = obj_type.name
  35. return JsonResponse({'book': books}, json_dumps_params={'ensure_ascii': False})
  • 图书关键字筛选
  1. # 前端 JavaScript代码
  2. // 入口函数添加 难度筛选事件
  3. // 指定关键字查询
  4. $('.btnquery').click(function (){
  5. // 获取输入字符串
  6. queryItems.inputstr = $('.querystr').val();
  7. // 实现查询
  8. queryBooks();
  9. });
  10. # 后端图书查询函数添加
  11. # 实现图书查询
  12. def query_books(request):
  13. # 获取传递来的条件
  14. type = request.POST.get('type')
  15. # 价格
  16. price_min = request.POST.get('pricemin')
  17. price_max = request.POST.get('pricemax')
  18. # 难度
  19. difficulty = request.POST.get('difficulty')
  20. # 输入的值
  21. input_str = request.POST.get('inputstr')
  22. if type == '0':
  23. obj_books = Book.objects.all().values()
  24. else:
  25. # 通过编号筛选出图书
  26. obj_books = Book.objects.filter(type_id=type).values()
  27. # 筛选价格
  28. obj_books = obj_books.filter(price__gte=price_min,price__lte=price_max)
  29. # 筛选难度
  30. if '0' not in difficulty:
  31. obj_books = obj_books.filter(difficulty=difficulty)
  32. # 输入筛选
  33. obj_books = obj_books.filter(name__icontains=input_str)
  34. books = list(obj_books.values())
  35. # 遍历图书 获取类别名称
  36. for index, item in enumerate(books):
  37. # 根据类别编号获取图书类别的对象
  38. obj_type = BookType.objects.get(id=item['type_id'])
  39. # 附加typename到当前成员
  40. books[index]['typename'] = obj_type.name
  41. return JsonResponse({'book': books}, json_dumps_params={'ensure_ascii': False})
  • 图书价格升降序排序
  1. # 前端 JavaScript代码
  2. // 入口函数添加 难度筛选事件
  3. // 指定关键字查询
  4. // 升序
  5. $('.asc').click(function (){
  6. // 把所有排序的图标不选择
  7. $('.asc').css('color','#fff');
  8. $('.desc').css('color','#fff');
  9. // 选中升序
  10. $('.asc').css('color','red');
  11. // 修改order
  12. queryItems.order = 1;
  13. // 提交给后端
  14. queryBooks();
  15. });
  16. // 降序
  17. $('.desc').click(function (){
  18. // 把所有排序的图标不选择
  19. $('.asc').css('color','#fff');
  20. $('.desc').css('color','#fff');
  21. // 选中升序
  22. $('.desc').css('color','red');
  23. // 修改order
  24. queryItems.order = 2;
  25. // 提交给后端
  26. queryBooks();
  27. });
  28. # 后端图书查询函数添加
  29. # 实现图书查询
  30. def query_books(request):
  31. # 获取传递来的条件
  32. type = request.POST.get('type')
  33. # 价格
  34. price_min = request.POST.get('pricemin')
  35. price_max = request.POST.get('pricemax')
  36. # 难度
  37. difficulty = request.POST.get('difficulty')
  38. # 输入的值
  39. input_str = request.POST.get('inputstr')
  40. # 升降序
  41. order = request.POST.get('order')
  42. if type == '0':
  43. obj_books = Book.objects.all().values()
  44. else:
  45. # 通过编号筛选出图书
  46. obj_books = Book.objects.filter(type_id=type).values()
  47. # 筛选价格
  48. obj_books = obj_books.filter(price__gte=price_min,price__lte=price_max)
  49. # 筛选难度
  50. if '0' not in difficulty:
  51. obj_books = obj_books.filter(difficulty=difficulty)
  52. # 输入筛选
  53. obj_books = obj_books.filter(name__icontains=input_str)
  54. # 排序
  55. if order == '1':
  56. obj_books = obj_books.order_by('price').all()
  57. elif order == '2':
  58. obj_books = obj_books.order_by('-price').all()
  59. books = list(obj_books.values())
  60. # 遍历图书 获取类别名称
  61. for index, item in enumerate(books):
  62. # 根据类别编号获取图书类别的对象
  63. obj_type = BookType.objects.get(id=item['type_id'])
  64. # 附加typename到当前成员
  65. books[index]['typename'] = obj_type.name
  66. return JsonResponse({'book': books}, json_dumps_params={'ensure_ascii': False})

图片懒加载

为了提高用户体验度,在长页面的时候,优先加载用户屏幕区域的内容,下拉的内容暂时不加载,等滚动条拖动的时候逐步加载。

  1. <!--引入图片懒加载js包LazyLoad-->
  2. <script src="{% static 'js/jquery.lazyload.min.js' %}"></script>
  3. // 修改addBooks
  4. function addBooks(books) {
  5. //清空区域内容
  6. $('.books').html("");
  7. //定义一个基础的URL
  8. let baseURL = "http://127.0.0.1:8000/";
  9. //遍历
  10. books.forEach(function (element, index, array) {
  11. //新建一个div-最外层的容器
  12. let outer = $('<div>').attr( "class", "col-lg-3");
  13. //新建一个div,设置类为thumbnail
  14. let thumbnail = $('<div>').attr( "class", "thumbnail").css('overflow','hidden').appendTo(outer);
  15. //******新建一个img标签,放置图片****
  16. let img = $('<img>')
  17. .attr('class','lazy')
  18. .attr('width','200px')
  19. .attr('height','200px')
  20. .attr('src', "{% static 'images/lazy.png' %}")
  21. .attr('data-original',baseURL+element.image)
  22. .appendTo(thumbnail)
  23. //img.lazyload();
  24. //设置图的hover过渡特效 --- 放大1.4
  25. img.on('mouseenter',function () {
  26. img.transition({ scale: 1.4 }, 300);
  27. }).on('mouseleave',function () {
  28. img.transition({ scale: 1 }, 300);
  29. });
  30. //新建一个div--放置价格
  31. let price = $('<div>').html("价格:" + element.price.toFixed(2) + "元").css('text-align', 'left').css('color','red').css('margin-top','20px').css('font-size','16px')
  32. .css('line-height', '30px').appendTo(thumbnail);
  33. {#$("<span>").html("类别:" + element.typename).css('text-align', 'left').css('font-size','16px')#}
  34. {# .css('line-height', '30px').appendTo(thumbnail);#}
  35. //新建一个div--放置图书名称
  36. let bookname =$('<div>').html(element.name).css('text-align', 'left').css('color','navy').css('font-size','16px').appendTo(thumbnail);
  37. //设置图书名称的 Hover
  38. bookname.on('mouseenter',function () {
  39. bookname.css('font-weight','bold');
  40. }).on('mouseleave',function () {
  41. bookname.css('font-weight','normal');
  42. });
  43. //展示类别
  44. let typeAndDiff = $("<div>");
  45. $("<span>").html("类别:" + element.typename).css('text-align', 'left').css('font-size','16px')
  46. .css('line-height', '30px').appendTo(typeAndDiff);
  47. $("<span>").html("&nbsp&nbsp&nbsp&nbsp难易程度:" + element.difficulty).css('text-align', 'left').css('font-size','16px')
  48. .css('line-height', '30px').appendTo(typeAndDiff);
  49. typeAndDiff.appendTo(thumbnail);
  50. //点击某一本触发的事件
  51. outer.click(function (){
  52. {#location.href = "/book/detail/" + element.id + "/";#}
  53. {#location.href = "/home/book/detail/?bookid=" + element.id;#}
  54. let temp = window.open('_blank');
  55. temp.location.href = "/home/book/detail/?bookid=" + element.id;
  56. });
  57. //把当前容器放置在页面上
  58. outer.appendTo($('.books'))
  59. });
  60. //设置图片懒加载
  61. $('img.lazy').lazyload({
  62. threshold: 200,
  63. effect: 'fadeIn'
  64. });
  65. }

添加图片详情功能

在图书列表页面点击某一本图书获取这本图书的图书编号,在跳转的时候,携带图书编号跳转到详情页,在详情页中通过携带过来的图书编号在数据库査询更多的信息在页面展示。

  1. # 详情页 html
  2. {% load static %}
  3. <!DOCTYPE html>
  4. <html lang="en">
  5. <head>
  6. <meta charset="UTF-8">
  7. <title>图书详情</title>
  8. <!-- 新 Bootstrap 核心 CSS 文件 -->
  9. <link href="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
  10. <link type="text/css" rel="stylesheet" href="{% static 'css/bookdetail.base.css' %}">
  11. <!-- jQuery文件。务必在bootstrap.min.js 之前引入 -->
  12. <script src="https://cdn.staticfile.org/jquery/2.1.1/jquery.min.js"></script>
  13. <!-- 最新的 Bootstrap 核心 JavaScript 文件 -->
  14. <script src="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script>
  15. </head>
  16. <body>
  17. <div class="container-fiuled header">
  18. <div class="container">
  19. <img src="{% static 'images/book_logo.png' %}">
  20. </div>
  21. </div>
  22. <div class="container title">图书详情</div>
  23. <div class="container basic">
  24. <div class="left" >
  25. </div>
  26. <div class="right" >
  27. </div>
  28. </div>
  29. <div class="container detail" style="padding: 25px; box-sizing: border-box">
  30. </div>
  31. </body>
  32. </html>
  1. # 设置 views.py视图
  2. def book_detail(request,bookid):
  3. print(bookid)
  4. """图书详情页"""
  5. return render(request, 'bookdetail.html',context={'bookid':bookid})
  6. # 获取图书详情
  7. def get_book_by_id(request):
  8. # 接收传递过来的 id
  9. bookid = request.POST.get('bookid')
  10. # bookid = '39001'
  11. # 获取book表信息
  12. obj_book = Book.objects.filter(id=bookid).values()[0]
  13. # 通过type_id 获取列表的对象
  14. obj_booktype = BookType.objects.get(id=obj_book['type_id'])
  15. # 通过Press_id 获取出版社的对象
  16. obj_press = Press.objects.get(id=obj_book['press_id'])
  17. # 通过author_id 获取作者的对象
  18. obj_author = Author.objects.get(id=obj_book['author_id'])
  19. # 组合拼接到obj_book
  20. obj_book['typename'] = obj_booktype.name
  21. obj_book['pressname'] = obj_press.name
  22. obj_book['authorname'] = obj_author.name
  23. # 返回
  24. return JsonResponse(obj_book)
  25. # 定义前端访问路由
  26. from django.urls import path
  27. from bookshop import views as bookshop_views
  28. urlpatterns = [
  29. # =========前端 url请求:返回页面============
  30. path('', bookshop_views.book, name='book'),
  31. path('book/detail/<bookid>/', bookshop_views.book_detail, name='bookdetail'),#图书详情页
  32. # =========后端 url请求:返回json数据========
  33. path('booktype/get/', bookshop_views.get_booktype, name='booktype'),
  34. path('books/get/', bookshop_views.get_books, name='books'),
  35. path('books/query/', bookshop_views.query_books, name='books_query'),
  36. path('books/get_detail/', bookshop_views.get_book_by_id, name='books_getdetail'),#获取某一图书详情
  37. ]
  1. // 前端 JavaScript
  2. <script>
  3. // 入口函数
  4. $(document).ready(function (){
  5. // 入口函数代码自动执行
  6. $.ajax({
  7. url: '/home/books/get_detail/',
  8. method: 'post',
  9. data: {
  10. 'bookid': {{ bookid }}
  11. },
  12. success: function (res){
  13. {#console.log(res)#}
  14. addBookDetail(res)
  15. }
  16. });
  17. // 展示图书信息
  18. function addBookDetail(book) {
  19. //清除图片区域
  20. let leftArea = $('.basic .left');
  21. leftArea.html("");
  22. //定义基础的URL
  23. BASE_URL = "http://127.0.0.1:8000/";
  24. //加载图书
  25. $('<img>').attr("width",'300px').attr('height',"300px").css('margin','50px')
  26. .attr('src', BASE_URL + book.image).appendTo(leftArea);
  27. //右边区域
  28. let rightArea = $('.basic .right');
  29. rightArea.html("");
  30. //编号
  31. let arr = ["id", "name",'authorname','price','typename','difficulty','pressname','publish_date','inventory_num'];
  32. let arr_name = ['编号','名称','作者','价格','类别','等级','出版社','出版时间','库存量'];
  33. let obj_ul = $('<ul>').css('font-size','16px');
  34. //循环
  35. for(let index in arr){
  36. let temp_li = $("<li>");
  37. $("<span>").css('color','red').html(arr_name[index]+":").appendTo(temp_li);
  38. $("<span>").css('color','#000').html("&nbsp;&nbsp;&nbsp;"+ book[arr[index]]).appendTo(temp_li);
  39. temp_li.appendTo(obj_ul);
  40. }
  41. obj_ul.appendTo(rightArea);
  42. //把图书的详情展示在页面
  43. $('.detail').html(book.detail);
  44. }
  45. })
  46. </script>

后台部署富文本编辑器

  • 安装模块
  1. pip install django-ckeditor==5.9.0
  2. pip install Pillow==6.2.0
  • 注册并添加配置
  1. INSTALLED_APPS = [
  2. 'django.contrib.admin',
  3. 'django.contrib.auth',
  4. 'django.contrib.contenttypes',
  5. 'django.contrib.sessions',
  6. 'django.contrib.messages',
  7. 'django.contrib.staticfiles',
  8. 'bookshop',
  9. 'xadmin',
  10. 'crispy_forms',
  11. 'crispy_bootstrap3',
  12. 'ckeditor',
  13. 'ckeditor_uploader'
  14. ]
  15. # ====添加CKEditor配置====
  16. # 使用默认的主题名称
  17. CKEDITOR_CONFIGS = {
  18. 'default':
  19. {
  20. 'toolbar': 'full',
  21. 'height': 500,
  22. 'width': 900,
  23. },
  24. }
  25. # 上传文件存储在哪个目录 /media/uploads/
  26. CKEDITOR_UPLOAD_PATH = "uploads/"
  • 配置url路由
  1. from django.urls import path
  2. # 调用其他app下定义的 url
  3. from django.urls import include
  4. # 引入 xadmin
  5. import xadmin
  6. from django.conf import settings
  7. # 匹配静态文件
  8. from django.conf.urls.static import static
  9. urlpatterns = [
  10. # path('admin/', admin.site.urls),
  11. path('xadmin/', xadmin.site.urls),
  12. # 富文本编辑器
  13. path('ckeditor/',include('ckeditor_uploader.urls')),
  14. path('home/', include('bookshop.urls'))
  15. ]
  16. # 允许所有的图片被访问
  17. urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
  • 模版models.py添加Book新字段
  1. from ckeditor_uploader.fields import RichTextUploadingField
  2. class Book(models.Model): # 图书
  3. id = models.CharField(primary_key=True, max_length=100, null=False, verbose_name='编号') # 编号,主键
  4. name = models.CharField(max_length=100, null=False, verbose_name='名称') # 名称
  5. barcode = models.CharField(max_length=100, null=False, verbose_name='条形码') # 条形码
  6. type = models.ForeignKey("BookType", on_delete=models.CASCADE, verbose_name='类别') # 类别
  7. press = models.ForeignKey("Press", on_delete=models.CASCADE, verbose_name='出版社') # 出版社
  8. author = models.ForeignKey("Author", on_delete=models.CASCADE, verbose_name='作者') # 作者
  9. price = models.FloatField(null=False, verbose_name='单价') # 价格
  10. difficulty = models.CharField(max_length=100,null=False, verbose_name='难易程度') # 难易程度: 0--入门 1--中级 2--高级
  11. # path="" 默认存储到media下 variations缩略图配置
  12. image = StdImageField(max_length=200, upload_to=UploadToUUID(path=""),
  13. verbose_name='图片', variations={'thumbnail': {'width': 70, 'height': 100}}
  14. )
  15. publish_date = models.DateField(null=False, verbose_name='发行时间') # 发行时间
  16. storage_in_num = models.IntegerField(null=False, verbose_name='入库量') # 入库量
  17. storage_in_date = models.DateField(null=False, verbose_name='入库时间') # 入库时间
  18. inventory_num = models.IntegerField(null=False, verbose_name='库存量') # 库存量
  19. # 添加富文本编辑器字段
  20. detail = RichTextUploadingField(verbose_name="图书详情",default="")
  21. class Meta:
  22. verbose_name = "图书"
  23. verbose_name_plural = "图书"
  24. def __str__(self):
  25. return "%s" % self.name
  • 同步数据
  1. python manage.py makemigrations
  2. python manage.py migrate
  • 将富文本内容展示在前端页面
  1. //把图书的详情展示在页面
  2. $('.detail').html(book.detail);

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/在线问答5/article/detail/938276
推荐阅读
相关标签
  

闽ICP备14008679号