号称最为简明实用的Django上手教程(下)
作者:白宁超
2017年8月25日08:51:58
摘要:上文 号称【最为简明实用的Django上手教程】介绍了django基本概念、配置和相关操作。相信通过上文的阅读,基本明白django运行机制和操作。假设你现在通过dome和相关书籍已经基本理解django这台机器的运行。下一步如何像asp.net、Jsp,PHP等常规网站开发,进行前后台交互呢?又如何采用较为简洁美观的前端框架进行设计呢?假设你需要配置多个数据库怎么办?静态文件单独存放需要哪些配置?针对这些配置有哪些便利?最后,假设你又是一名对数据开发很感兴趣的,且学过一些机器学习,数据挖掘,自然语言处理,云计算等技术之一,想挖掘分析数据并进行可视化,怎么办?本文就是针对这些问题开始的。 (本文原创编著,转载注明出处:号称最为简明实用的Django上手教程(下))
1 前景回顾
系统环境:WIN10 64bit
开发环境:sublime+Anaconda
数据库:Mysql 5.6.17
语言:python3.5
框架:django1.11+Bootstrap
可视化工具:Highchart|Echarts|plotly|Bokeh(采用Echarts)
2 静态文件配置操作
(1)静态static文件夹的配置。
在analysis文件夹下创建:analysis/static和analysis/templates文件夹,其中:
① static:包括,css,js,img,font,files等文件,使用时需要配置,页面开头添加{% load static %}
② templates:包含web的html静态页面,django1.10之后会默认识别
(2)打开xmjc_analysis/setting.py修改如下:
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, "static")
(3)打开xmjc_analysis/urls.py修改如下:
# 配置加载静态页面
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^index/$', analysis_views.index,name='index'),# 首页
]+ static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
(4) 在基模板(后文详细介绍)base页面开头添加{% load static %}
(5 )xmjc_analysis/views.py修改如下:
'''
第一个页面
author:白宁超
site:http://www.cnblogs.com/baiboy/
'''
#coding:utf-8
from django.shortcuts import render
from django.http import HttpResponse
def index1(request):
name = request.GET['name']
return HttpResponse(u"欢迎"+name+",进入第一个Django页面!")
def index(request):
'''项目统计分析平台主页'''
return render(request,'xmjc/index.html') # 首页
然后在xmjc_analysis/urls.py下添加访问
前端nav.html的超链接如下:
3 结合Bootstrap和页面模板前端设计
(1)什么是Bootstrap?
Bootstrap是一组用于网站和网络应用程序开发的开源前端框架,包括HTML、CSS及JavaScript的框架,提供字体排印、窗体、按钮、导航及其他各种组件及Javascript扩展,旨在使动态网页和Web应用的开发更加容易。 Bootstrap是GitHub上面被标记为“Starred”次数排名第二最多的项目。Starred次数超过105,000,而分支次数超过了47,000次。
ps:前端框架,所有的插件依赖于 jQuery。所以必须在插件文件之前引用 jQuery
----维基百科
(2)Bootstrap学习资料
① 官网下载地址:http://getbootstrap.com/
② 中文网下载地址:http://www.bootcss.com/
③ w3c学习网站:https://www.w3cschool.cn/bootstrap
(3)引入 Bootstrap
具体知识点总结参考文章:【前端知识十分钟预览之学习札记】
(4)基于Bootstrap的页面模板设计
① base.html 可以视作母模板,其中包括:
{% load static %} 放在页面最顶层,用于识别静态文件
放入的编码和基本信息以及css文件(js文件放在页面尾部,提高用户体验)
侧边栏 引用③文件,便于修改和管理。
页面内容设计 {% block content %}{% endblock %}占块符号
{% block content %}
此处为主要内容
{% endblock %}
底部 存放js文件
{% load static %} "content-type" content="text/html; charset=UTF-8"> "utf-8"> "author" content="bnc"> "stylesheet" type="text/css" href="/static/bootstrap-dist/css/bootstrap.min.css" /> "stylesheet" type="text/css" href="/static/bootstrap-dist/css/bootstrap-theme.css" /> "stylesheet" type="text/css" href="/static/css/cloud-admin.css" /> "stylesheet" type="text/css" href="/static/css/themes/default.css" id="skin-switcher" /> "/static/font-awesome/css/font-awesome.min.css" rel="stylesheet"/> "stylesheet" type="text/css" href="/static/js/jquery-ui-1.10.3.custom/css/custom-theme/jquery-ui-1.10.3.custom.min.css" /> "stylesheet" type="text/css" href="/static/js/datatables/media/css/jquery.dataTables.min.css" /> "stylesheet" type="text/css" href="/static/js/datatables/media/assets/css/datatables.min.css" /> "stylesheet" type="text/css" href="/static/js/datatables/extras/TableTools/media/css/TableTools.min.css" />{% block title %}四川省科技厅大数据决策分析平台{% endblock %} class="navbar clearfix" id="header"> class="container">class="navbar-brand "> "{% url 'index' %}"> "/static/img/logo/logo.png" alt="" class="img-responsive" height="30" width="120">"sidebar-collapse" class="sidebar-collapse btn"> class="fa fa-bars" data-icon1="fa fa-bars" data-icon2="fa fa-bars" >class="nav navbar-nav pull-left hidden-xs" id="navbar-left">
- class="dropdown"> "{% url 'index' %}" class="team-status-toggle dropdown-toggle tip-bottom" data-toggle="tooltip" title="大数据决策分析平台"> class="name" style="font-size: x-large;">大数据决策分析平台
class="nav navbar-nav pull-right" style="float: right;margin-right: -6%">
- class="dropdown" id="header-notification"> "#" class="dropdown-toggle" data-toggle="dropdown"> class="fa fa-bell"> class="badge">7
class="dropdown-menu notification">
- class="dropdown-title"> class="fa fa-bell"> 6 消息通知
- "#"> class="label label-success">class="fa fa-user"> class="body"> class="message">5 用户在线. class="time"> class="fa fa-clock-o"> 刚刚
- "#"> class="label label-warning">class="fa fa-lock"> class="body"> class="message">DW1 服务器停止. class="time"> class="fa fa-clock-o"> 32 分钟前
- class="footer"> "#">查看所有通知信息 class="fa fa-arrow-circle-right">
- class="dropdown user" id="header-user"> "#" class="dropdown-toggle" data-toggle="dropdown"> "" src="/static/img/avatars/avatar3.jpg" /> class="username">王定国 class="fa fa-angle-down">
class="dropdown-menu">
- "#">class="fa fa-user">个人简介
- "#">class="fa fa-cog"> 账号设置
- "login.html">class="fa fa-power-off">退 出
"page"> "sidebar" class="sidebar"> {% include 'xmjc/nav.html' %}"main-content">class="container">class="row">"content" class="col-lg-12">class="row col-lg-12">class="page-header">class="breadcrumb">
- class="fa fa-home"> "{% url 'index' %}">首页
- {% block lnav %} 菜单导航 {% endblock %}
class="clearfix">class="content-title pull-left"> {{ lnav }}
class="description"> {{ lcontent }}class="row col-lg-12"> {% block content %}此处为主要内容
{% endblock %}class="footer-tools"> class="go-top"> class="fa fa-chevron-up"> 顶部
② content.html 内容页面,可以自己自由设计,本例子使用画布布局,展示几个可视化和表格的应用。
class="row">class="col-md-6">class="row">class="col-lg-6">class="dashbox panel panel-default">class="panel-body">class="panel-left red"> class="fa fa-instagram fa-3x">class="panel-right">class="number">6718class="title">Likesclass="label label-success"> 26% class="fa fa-arrow-up">class="col-lg-6">class="dashbox panel panel-default">class="panel-body">class="panel-left blue"> class="fa fa-twitter fa-3x">class="panel-right">class="number">2724class="title">Followersclass="label label-warning"> 5% class="fa fa-arrow-down">class="row">class="col-md-12">class="quick-pie panel panel-default">class="panel-body">class="col-md-4 text-center">"dash_pie_1" class="piechart" data-percent="59"> class="percent">"#" class="title">New Visitors class="fa fa-angle-right">class="col-md-4 text-center">"dash_pie_2" class="piechart" data-percent="73"> class="percent">"#" class="title">Bounce Rate class="fa fa-angle-right">class="col-md-4 text-center">"dash_pie_3" class="piechart" data-percent="90"> class="percent">"#" class="title">Brand Popularity class="fa fa-angle-right">class="col-md-6">class="box solid grey">class="box-title">class="fa fa-dollar">Revenue
class="tools"> class="label label-danger"> 20% class="fa fa-arrow-up"> "#box-config" data-toggle="modal" class="config"> class="fa fa-cog"> "javascript:;" class="reload"> class="fa fa-refresh"> "javascript:;" class="collapse"> class="fa fa-chevron-up"> "javascript:;" class="remove"> class="fa fa-times">class="box-body">"chart-revenue" style="height:240px">class="row">class="col-md-6">class="box border">class="box-title">class="fa fa-columns"> class="hidden-inline-mobile">Sales Tab
class="box-body">class="tabbable header-tabs">class="nav nav-tabs">
- class="active">"#sales" data-toggle="tab">class="fa fa-bookmark"> class="hidden-inline-mobile">New Orders
- "#feed" data-toggle="tab">class="fa fa-rss"> class="hidden-inline-mobile">Recent Activities
class="tab-content">class="tab-pane active" id="sales">class="panel panel-default">class="panel-body orders no-opaque">class="scroller" data-height="450px" data-always-visible="1" data-rail-visible="1">class="list-unstyled">
- class="clearfix">
class="pull-left">
#A14 Rikki S. Stover
class="fa fa-clock-o"> class="timeago" title="Oct 9, 2013" >Oct 9, 2013
class="text-right pull-right">class="cost">$124.00
class="label label-success arrow-in-right">class="fa fa-check"> Complete
class="clearfix">class="progress progress-sm">class="progress-bar progress-bar-success" role="progressbar" aria-valuenow="85" aria-valuemin="0" aria-valuemax="100" style="width: 85%;"> class="sr-only">85% Complete- class="clearfix">
class="pull-left">
#A15 Scott Allen
class="fa fa-clock-o"> class="timeago" title="Oct 10, 2013" >Oct 10, 2013
class="text-right pull-right">class="cost">$235.00
class="label label-warning arrow-in-right">class="fa fa-cog"> In Progress
class="clearfix">class="progress progress-sm">class="progress-bar progress-bar-warning" role="progressbar" aria-valuenow="30" aria-valuemin="0" aria-valuemax="100" style="width: 30%;"> class="sr-only">30% Complete- class="clearfix">
class="pull-left">
#A16 Larry Wright
class="fa fa-clock-o"> class="timeago" title="Oct 11, 2013" >Oct 11, 2013
class="text-right pull-right">class="cost">$77.00
class="label label-primary arrow-in-right">class="fa fa-archive"> Archived
class="clearfix">class="progress progress-sm">class="progress-bar progress-bar-primary" role="progressbar" aria-valuenow="97" aria-valuemin="0" aria-valuemax="100" style="width: 97%;"> class="sr-only">97% Complete- class="clearfix">
class="pull-left">
#A17 John Dale
class="fa fa-clock-o"> class="timeago" title="Oct 10, 2013" >Oct 10, 2013
class="text-right pull-right">class="cost">$174.00
class="label label-danger arrow-in-right">class="fa fa-star"> New
class="clearfix">class="progress progress-sm">class="progress-bar progress-bar-danger" role="progressbar" aria-valuenow="10" aria-valuemin="0" aria-valuemax="100" style="width: 10%;"> class="sr-only">10% Complete- class="clearfix">
class="pull-left">
#A18 MJ Perkins
class="fa fa-clock-o"> class="timeago" title="Oct 11, 2013" >Oct 11, 2013
class="text-right pull-right">class="cost">$68.00
class="label label-info arrow-in-right">class="fa fa-truck"> In Transit
class="clearfix">class="progress progress-sm">class="progress-bar progress-bar-info" role="progressbar" aria-valuenow="50" aria-valuemin="0" aria-valuemax="100" style="width: 50%;"> class="sr-only">50% Complete- class="clearfix">
class="pull-left">
#A19 Stephen Stover
class="fa fa-clock-o"> class="timeago" title="Oct 9, 2013" >Oct 9, 2013
class="text-right pull-right">class="cost">$124.00
class="label label-success arrow-in-right">class="fa fa-check"> Complete
class="clearfix">class="progress progress-sm">class="progress-bar progress-bar-success" role="progressbar" aria-valuenow="80" aria-valuemin="0" aria-valuemax="100" style="width: 80%;"> class="sr-only">80% Complete- class="clearfix">
class="pull-left">
#A20 Edward Lus
class="fa fa-clock-o"> class="timeago" title="Oct 11, 2013" >Oct 11, 2013
class="text-right pull-right">class="cost">$52.00
class="label label-danger arrow-in-right">class="fa fa-star"> New
class="clearfix">class="progress progress-sm">class="progress-bar progress-bar-danger" role="progressbar" aria-valuenow="20" aria-valuemin="0" aria-valuemax="100" style="width: 20%;"> class="sr-only">20% Complete- class="clearfix">
class="pull-left">
#A21 Alice Mangrum
class="fa fa-clock-o"> class="timeago" title="Oct 11, 2013" >Oct 11, 2013
class="text-right pull-right">class="cost">$14.00
class="label label-info arrow-in-right">class="fa fa-truck"> In Transit
class="clearfix">class="progress progress-sm">class="progress-bar progress-bar-info" role="progressbar" aria-valuenow="65" aria-valuemin="0" aria-valuemax="100" style="width: 65%;"> class="sr-only">65% Complete- class="clearfix">
class="pull-left">
#A22 Tamika Owens
class="fa fa-clock-o"> class="timeago" title="Oct 11, 2013" >Oct 11, 2013
class="text-right pull-right">class="cost">$604.00
class="label label-warning arrow-in-right">class="fa fa-cog"> In Progress
class="clearfix">class="progress progress-sm">class="progress-bar progress-bar-warning" role="progressbar" aria-valuenow="75" aria-valuemin="0" aria-valuemax="100" style="width: 75%;"> class="sr-only">75% Completeclass='text-center'>class='pagination'>
- class='disabled'> '#'> class='fa fa-angle-left'>
- class='active'> '#'> 1
- '#'>2
- '#'>3
- '#'>4
- '#'>5
- '#'> class='fa fa-angle-right'>
class="tab-pane" id="feed">class="scroller" data-height="450px" data-always-visible="1" data-rail-visible="1">class="feed-activity clearfix">class="pull-left roundicon fa fa-check btn btn-info"> class="user" href="#"> John Doe accepted your connection request.
"#">View profileclass="time"> class="fa fa-clock-o"> 5 hours agoclass="feed-activity clearfix">class="pull-left roundicon fa fa-picture-o btn btn-danger"> class="user" href="#"> Jack Doe uploaded a new photo.
"#">Take a lookclass="time"> class="fa fa-clock-o"> 5 hours agoclass="feed-activity clearfix">class="pull-left roundicon fa fa-edit btn btn-pink"> class="user" href="#"> Jess Doe edited their skills.
"#">Endorse themclass="time"> class="fa fa-clock-o"> 5 hours agoclass="feed-activity clearfix">class="pull-left roundicon fa fa-bitcoin btn btn-yellow"> class="user" href="#"> Divine Doe made a bitcoin payment.
"#">Check your financialsclass="time"> class="fa fa-clock-o"> 6 hours agoclass="feed-activity clearfix">class="pull-left roundicon fa fa-dropbox btn btn-primary"> class="user" href="#"> Lisbon Doe saved a new document to Dropbox.
"#">Downloadclass="time"> class="fa fa-clock-o"> 1 day agoclass="feed-activity clearfix">class="pull-left roundicon fa fa-pinterest btn btn-inverse"> class="user" href="#"> Bob Doe pinned a new photo to Pinterest.
"#">Take a lookclass="time"> class="fa fa-clock-o"> 2 days agoclass="feed-activity clearfix">class="pull-left roundicon fa fa-clock-o btn btn-success"> class="user" href="#"> John Doe accepted your connection request.
"#">View profileclass="time"> class="fa fa-clock-o"> 5 hours agoclass="feed-activity clearfix">class="pull-left roundicon fa fa-heart btn btn-purple"> class="user" href="#"> Jack Doe uploaded a new photo.
"#">Take a lookclass="time"> class="fa fa-clock-o"> 5 hours agoclass="feed-activity clearfix">class="pull-left roundicon fa fa-gift btn btn-pink"> class="user" href="#"> Jess Doe edited their skills.
"#">Endorse themclass="time"> class="fa fa-clock-o"> 5 hours agoclass="feed-activity clearfix">class="pull-left roundicon fa fa-random btn btn-yellow"> class="user" href="#"> Divine Doe made a bitcoin payment.
"#">Check your financialsclass="time"> class="fa fa-clock-o"> 6 hours agoclass="col-md-6">class="row">class="col-md-6">class="box border inverse">class="box-title">class="fa fa-money">Sales Summary
class="box-body">class="sparkline-row"> class="title">Total sales class="value">$78,273 class="sparkline big" data-color="blue">16,7,23,13,12,11,15,4,19,18,4,24class="sparkline-row"> class="title">Profit class="value">$6,543 class="sparkline big" data-color="red">6,3,24,25,27,29,14,26,20,8,12,20class="sparkline-row"> class="title">Orders class="value">985 class="sparkline big" data-color="green">11,19,20,20,5,18,11,6,16,20,26,11class="col-md-6">class="box border purple">class="box-title">class="fa fa-adjust">Distribution Index
class="box-body">class="sparkline-row"> class="title">Revenue distribution class="value">class="fa fa-usd"> 25674 class="sparklinepie">16,7,23class="sparkline-row"> class="title">Sales class="value">class="fa fa-money"> 19 999,99 class="sparklinepie">6,3,24,25class="sparkline-row"> class="title">Employee/ Dept class="value">class="fa fa-user"> 645783 class="sparklinepie">11,19,20class="col-md-6">class="panel panel-default">class="panel-body">class="table table-striped table-bordered table-hover">
class="fa fa-user"> Client class="hidden-xs">class="fa fa-quote-left"> Sales Item class="fa fa-dollar"> Amount class="fa fa-bars"> Status "#">Fortune 500 class="hidden-xs">Gold Level Virtual Server $ 2310.23 class="label label-success label-sm">Paid "#">Cisco Inc. class="hidden-xs">Platinum Level Virtual Server $ 5502.67 class="label label-warning label-sm">Pending "#">VMWare Ltd. class="hidden-xs">Hardware Switch $ 3472.54 class="label label-success label-sm">Paid "#">Wall-Mart Stores class="hidden-xs">Branding & Marketing $ 6653.25 class="label label-success label-sm">Paid "#">Exxon Mobil class="hidden-xs">UX and UI Services $ 45645.45 class="label label-danger label-sm">Overdue "#">General Electric class="hidden-xs">Web Designing $ 3432.11 class="label label-warning label-sm">Pending
③ nav.html 导航页面设计,其中包括菜单折叠,子菜单等功能,超链接使用
class="sidebar-menu nav-collapse">class="divide-20">"search-bar"> class="search" type="text" placeholder="查找">class="fa fa-search search-icon">
- class="active"> "{% url 'index' %}"> class="fa fa-tachometer fa-fw"> class="menu-text">大数据决策分析 class="selected">
- class="has-sub"> "javascript:;" class=""> class="fa fa-bookmark-o fa-fw"> class="menu-text">项目统计分析 class="arrow">
class="sub">
- class="" href="{% url 'xmksh' %}"> class="sub-menu-text">可视化统计图形测试
- class="" href="{% url 'xmjf' %}"> class="sub-menu-text">项目经费统计
- class="" href=""> class="sub-menu-text">项目数量统计
- class="" href=""> class="sub-menu-text">项目区域统计
- class="" href="charts/xmlb.html"> class="sub-menu-text">项目类别统计
- class="has-sub-sub"> "javascript:;" class=""> class="sub-menu-text">项目结题统计 class="arrow">
- class="has-sub"> "javascript:;" class=""> class="fa fa-table fa-fw"> class="menu-text">市县州主题分析 class="arrow">
- class="has-sub"> "javascript:;" class=""> class="fa fa-pencil-square-o fa-fw"> class="menu-text">高校项目分布 class="arrow">
- class="has-sub"> "javascript:;" class=""> class="fa fa-bar-chart-o fa-fw"> class="menu-text">年报分析 class="arrow">
- class="has-sub"> "javascript:;" class=""> class="fa fa-columns fa-fw"> class="menu-text">专家人员统计分析 class="arrow">
- class="has-sub"> "javascript:;" class=""> class="fa fa-map-marker fa-fw"> class="menu-text">评奖情况统计分析 class="arrow">
- class="has-sub"> "javascript:;" class=""> class="fa fa-file-text fa-fw"> class="menu-text">机器学习算法库 class="arrow">
- class="has-sub"> "javascript:;" class=""> class="fa fa-file-text fa-fw"> class="menu-text">可视化图形库 class="arrow">
- class="has-sub"> "javascript:;" class=""> class="fa fa-briefcase fa-fw"> class="menu-text">数据预处理 class="badge pull-right">3 class="arrow">
- class="has-sub"> "javascript:;" class=""> class="fa fa-briefcase fa-fw"> class="menu-text">基础算法库 class="badge pull-right">3 class="arrow">
- class="" href="inbox.html"> class="fa fa-envelope-o fa-fw"> class="menu-text">邮件
- class="" href="widgets_box.html"> class="fa fa-th-large fa-fw"> class="menu-text">系统设置 class="tooltip-error pull-right" title="" data-original-title="3 New Events"> class="label label-success">新
- class="" href="../../static/frontend_theme/index.html" target="_blank"> class="fa fa-desktop fa-fw"> class="menu-text">前端主题
④ 首页 index.html 调用①母版页面,自定义内容
{% extends 'xmjc/base.html' %}
{% block title %}欢迎光临首页{% endblock %}
{% block content %}
{% include 'xmjc/content.html' %}
{% endblock %}
(5)运行服务器访问
页面效果:
至此,已经完成静态页面的配置工作。
4 多数据库配置联合操作
(1)打开xmjc_analysis/setting.py,有一个默认的数据库 default,我们可以再加一些其它的(这里你可以调用Access、SQLServer、Oracle等),比如:
'''
配置Mysql数据库
2017年7月26日16:40:38
白宁超
'''
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'test',
'USER': 'test',
'PASSWORD': 'test123',
'HOST':'localhost',
'PORT':'3306',
},
'db1': {
'ENGINE': 'django.db.backends.mysql',
'NAME': '数据库名称',
'USER': '用户名',
'PASSWORD': '密码',
"HOST": "localhost", #本地
'PORT':'3306',
},
'db2': {
'ENGINE': 'django.db.backends.mysql',
'NAME': '数据库名称',
'USER': '用户名',
'PASSWORD': '密码',
"HOST": "服务器地址",
'PORT':'3306',
},
}
# use multi-database in django
DATABASE_ROUTERS = ['xmjc_analysis.database_router.DatabaseAppsRouter']
DATABASE_APPS_MAPPING = {
#'app_name':'database_name',
'app1': 'db1',
'app2': 'db2',
}
(2)在project_name文件夹中存放 database_router.py 文件,内容如下:
# -*- coding: utf-8 -*- from django.conf import settings DATABASE_MAPPING = settings.DATABASE_APPS_MAPPING class DatabaseAppsRouter(object): """ A router to control all database operations on models for different databases. In case an app is not set in settings.DATABASE_APPS_MAPPING, the router will fallback to the `default` database. Settings example: DATABASE_APPS_MAPPING = {'app1': 'db1', 'app2': 'db2'} """ def db_for_read(self, model, **hints): """"Point all read operations to the specific database.""" if model._meta.app_label in DATABASE_MAPPING: return DATABASE_MAPPING[model._meta.app_label] return None def db_for_write(self, model, **hints): """Point all write operations to the specific database.""" if model._meta.app_label in DATABASE_MAPPING: return DATABASE_MAPPING[model._meta.app_label] return None def allow_relation(self, obj1, obj2, **hints): """Allow any relation between apps that use the same database.""" db_obj1 = DATABASE_MAPPING.get(obj1._meta.app_label) db_obj2 = DATABASE_MAPPING.get(obj2._meta.app_label) if db_obj1 and db_obj2: if db_obj1 == db_obj2: return True else: return False return None # for Django 1.4 - Django 1.6 def allow_syncdb(self, db, model): """Make sure that apps only appear in the related database.""" if db in DATABASE_MAPPING.values(): return DATABASE_MAPPING.get(model._meta.app_label) == db elif model._meta.app_label in DATABASE_MAPPING: return False return None # Django 1.7 - Django 1.11 def allow_migrate(self, db, app_label, model_name=None, **hints): print(db, app_label, model_name, hints) if db in DATABASE_MAPPING.values(): return DATABASE_MAPPING.get(app_label) == db elif app_label in DATABASE_MAPPING: return False return None
(3)使用操作
# 查询 YourModel.objects.using('db1').all() # 保存 或 删除 user_obj.save(using='new_users') user_obj.delete(using='legacy_users') # 数据库同步 python manage.py migrate --database=db2 # 数据导出 python manage.py dumpdata app2 --database=db2 > app2_fixture.json python manage.py dumpdata auth > auth_fixture.json # 数据库导入 python manage.py loaddata app1_fixture.json --database=db1
5 数据挖掘与可视化技术
(1)设计思路
调用Echarts进行可视化展示,其中数据来源于两个部分,直接调用一方面数据库的结构化数据,另一个方面分析处理非结构化数据。最终处理成json形式,最后结合ajax进行数据绑定展示。这里【数据挖掘|文本处理技术】不详细介绍,主要展示思想和流程。期望展示三个案例:柱形图、饼形图、数据表格。
(2)数据前台展示,使用表单需要添加{%csrf_token%}
(3)柱形图案例展示
新建页面ksh.html,添加如下代码
js代码:
/*
柱状图
白宁超
2017年8月4日17:20:42
*/
// 基于准备好的dom,初始化echarts图表
var myChart = echarts.init(document.getElementById('test1'));
// 指定图表的配置项和数据
var option = {
title: {
text: 'ECharts 入门示例'
},
tooltip: {},
legend: {
data:['销量']
},
xAxis: {
data: ["衬衫","羊毛衫","雪纺衫","裤子","高跟鞋","袜子"]
},
yAxis: {
},
series: [{
name: '销量',
type: 'bar',
data: [5, 20, 36, 10, 10, 20]
}]
};
// 使用刚指定的配置项和数据显示图表。
myChart.setOption(option);
json数据:上面案例采用官方数据,只需要配置data即可,这个data的json数据,你可以通过数据挖掘技术后文本或者数据库梳理出绑定起来即可。如下所示:
def xmjf(request):
lnav="项目经费统计" # 可视化主题
lcontent = "这里是可视化主题的描述->项目经费统计" # 可视化主题的描述
data=[{"value": 55, "name": '优先55'},
{"value": 70, "name": '普通70'},
{"value": 25, "name": "紧急25"}]
data1 = [{"keys":"衬衫", "values":5},
{"keys":"羊毛衫", "values":20},
{"keys":"雪纺衫", "values":36},
{"keys":"裤子", "values":10},
{"keys":"高跟鞋", "values":10},
{"keys":"袜子", "values":20}]
return render(request,'xmjc/xmjf.html',{'lnav':lnav,'lcontent':lcontent,'data':data,'data1':data1})
效果:
(4)扇形图案例展示
新建页面ksh.html,添加如下代码
js代码
/* 嵌套环形图 白宁超 2017年8月4日17:21:03 */ var myChart1 = echarts.init(document.getElementById('test2')); option1 = { tooltip: { trigger: 'item', formatter: "{a}
{b}: {c} ({d}%)" }, legend: { orient: 'vertical', x: 'left', data:['直达','营销广告','搜索引擎','邮件营销','联盟广告','视频广告','百度','谷歌','必应','其他'] }, series: [ { name:'访问来源', type:'pie', selectedMode: 'single', radius: [0, '30%'], label: { normal: { position: 'inner' } }, labelLine: { normal: { show: false } }, data:[ {value:335, name:'直达', selected:true}, {value:679, name:'营销广告'}, {value:1548, name:'搜索引擎'} ] }, { name:'访问来源', type:'pie', radius: ['40%', '55%'], data:[ {value:335, name:'直达'}, {value:310, name:'邮件营销'}, {value:234, name:'联盟广告'}, {value:135, name:'视频广告'}, {value:1048, name:'百度'}, {value:251, name:'谷歌'}, {value:147, name:'必应'}, {value:102, name:'其他'} ] } ] }; myChart1.setOption(option1);
效果
(5)表格案例展示
新建页面ksh.html,添加如下代码
class="row">class="col-md-6">class="box border green">class="box-title">class="fa fa-table">动态数据表格
class="box-body">"datatable1" cellpadding="0" cellspacing="0" border="0" class="datatable table table-striped table-bordered table-hover">
"tbody"> {% for user in data %} class="center">用户名 class="center">密码 class="center">邮箱 class="center">权限 class="gradeB"> {% endfor %}class="center">{{ user.username }} class="center">{{ user.userpass }} class="center">{{ user.useremail }} class="center">{{ user.usertype }} class="center">用户名 class="center">密码 class="center">邮箱 class="center">权限
效果
6 将项目上传到github,进行项目管理
(1)下载:Git 各平台安装包下载地址为:http://git-scm.com/downloads
pip install git-core
Windows 平台上安装包下载地址:http://msysgit.github.io/
(2)使用:Windows版Git下载安装,在开始菜单里找到Git->Git Bash
(3)配置你的名字和Email地址。
$ git config --global user.name "Your Name"
$ git config --global user.email "[email protected]"
(4)创建版本库
$ cd /E //你指定的个人盘符
$ mkdir mygit //创建版本库根目录
$ cd mygit //进入版本库目录
$ pwd //查看当前路径
(5) 将需要上传的项目拷贝到版本库即mygit里面,查看
(6)通过git init命令把目录变成Git可以管理的仓库
(7) mygit下创建xmjc_analysis,用命令git add告诉Git,把文件添加到仓库
(8)用命令git commit提交到仓库,-m本次提交的说明
(9)远程连接仓库
git remote add originbnc [email protected]:username/bncgit.git
(10)推送
git push -u originbnc master
(11)查看我的github
自此,完成全部初级学习,扩展处读者自行学习。