django+mysql+echarts实现数据可视化到前端

文章目录

  • 前言
  • 前提
  • 一、主要功能模块代码
  • 下面开始编写项目代码:
    • 1.Views.py——视图函数:主要功能是编写函数方法,与Urls(路由)的连接实现方法的实现
      • 1.引入所需库
      • 2.编写用户注册和登录模块
      • 3.编写购物信息模块
      • 4.编写与前端交互模块
      • 5. 与数据库交互取出数据模块
    • 2.Urls.py——路由:设置项目启动后的路由地址
      • 1.导入所需库
      • 2.编写URL
    • 3.settings.py——项目配置文件,项目中的所有功能都需要在该文件中进行配置
    • 4.Models.py——模型:定义数据库的映射类,每个类关联一张数据表,实现持久化,即MVT里面的模型
      • 1.引入库
      • 2.编写代码建立模型与数据库中的表进行连接
  • 二、HTML模板
    • 1.addlogin.html
    • 2.login
  • 总结


前言

基于django前端,并于后端数据库交互,通过百度开源的Echarts渲染图标进行数据可视化的系统设计与实现,同时兼顾登录注册功能和基本的用户增删改查。

前提

已经使用django,创建了一个django项目。


一、主要功能模块代码

介绍:Django 是基于Python 的一种Web框架,该框架是以MVT架构的前端展示。
django+mysql+echarts实现数据可视化到前端_第1张图片

下面开始编写项目代码:

1.Views.py——视图函数:主要功能是编写函数方法,与Urls(路由)的连接实现方法的实现

1.引入所需库

from django.shortcuts import render
from django.http import HttpResponse,JsonResponse
from myapp.models import login_model,age_1_model,sex_model,fav_model,foodtype_age_model,foodtype_model,foodtype_fav_model,foodtype_sex_model,user_model
from django.core.paginator import Paginator
from django.shortcuts import redirect
from django.core.urlresolvers import reverse

其中第三列,导入的为项目中models文件下的模型

2.编写用户注册和登录模块

# 登录页面
def loging(request):
    #request.session['uipuser'] = 'lin'
    print(request.session.get('vipuser',None))
    return render(request,"cslogin/loging.html")

# 跳转到首页
def dologin(request):
    user = login_model.objects.get(username = request.POST['username'])
    if user.state == 0:
        if user.password == request.POST['userpwd']:
            request.session['vipuser'] = user.username
            return redirect(reverse('index'))
        else:
            context = {"info":"密码错误"}
    else:
        context = {"info":"非vip请先注册"}
    return render(request,"cslogin/loging.html",context)

def addlogin_admin(request):
    return render(request,"cslogin/addlogin.html")

def addlogin(request):
    user = login_model()
    user.username = request.POST['name']
    user.password = request.POST['password']
    user.state = request.POST['state']
    user.save()
    print("管理员注册成功")
    return render(request,'cslogin/loging.html')

def logout(request):
    del request.session['vipuser']
    return render(request,"cslogin/loging.html")

3.编写购物信息模块

# 购物信息管理
def index(request):
    userList = user_model.objects.all()
    info = {"userList":userList}
    return render(request,"user/index.html",info)

def index_fen(request,pIndex):
	userList = user_model.objects.all()
	p = Paginator(userList,11)
	if pIndex == " ":
		pIndex="1"
	list2 = p.page(pIndex)
	plist = p.page_range
	context = {}
	context['userList'] = list2
	context["plist"] = plist
	return render(request,"user/index.html",context)

def add(request):
	return render(request,"user/add.html")

def insert(request):
    userlist = user_model()
    userlist.id = request.POST['id']
    userlist.foodtype = request.POST['foodtype']
    userlist.sex = request.POST['sex']
    userlist.age = request.POST['age']
    userlist.fav = request.POST['fav']
    userlist.save()
    info = {"info":"添加用户成功"}
    return render(request,'user/info.html',info)

def delete(request,uid):
	ob = user_model.objects.get(id=uid)
	ob.delete()
	info = {"info":"删除用户成功"}
	return render(request,'user/info.html',info)

def edit(request,uid):
	ob = user_model.objects.get(id=uid)
	info = {"user":ob}
	return render(request,'user/edit.html',info)

def update(request):
    userlist = user_model.objects.get(id=request.POST['id'])
    userlist.foodtype = request.POST['foodtype']
    userlist.sex = request.POST['sex']
    userlist.age = request.POST['age']
    userlist.fav = request.POST['fav']
    userlist.save()
    info = {"info":"修改成功!"}
    return render(request,"user/info.html",info)

4.编写与前端交互模块

# 前端显示统计结果页面
# index_age 返回页面
def index_age(request):
    return render(request,"sj/index_age.html")

# index_sex 返回页面
def index_sex(request):
    return render(request,"sj/index_sex.html")

# index_fav 返回页面
def index_fav(request):
    return render(request,"sj/index_fav.html")

# index_foodtype 返回页面
def index_foodtype(request):
    return render(request,"sj/index_foodtype.html")

# index_foodtype_age 返回页面
def index_foodtype_age(request):
    return render(request,"sj/food/index_foodtype_age.html")

# index_foodtype_sex 返回页面
def index_foodtype_sex(request):
    return render(request,"sj/food/index_foodtype_sex.html")

# index_foodtype_fav 返回页面
def index_foodtype_fav(request):
    return render(request,"sj/food/index_foodtype_fav.html")

5. 与数据库交互取出数据模块

# 从MySQL中读取data,并通过Ajax返回给html界面
# 读取年龄
def age(request):
    users = age_1_model.objects.all()
    age = []
    sum = []
    for user in users:
         age.append(user.age)
         sum.append(user.sum)
    user_dict = {}
    user_dict['age'] = age
    user_dict['sum'] = sum
    return JsonResponse(user_dict)

# 读取食品类型
def foodtype(request):
    users = foodtype_model.objects.all()
    foodtype = []
    sum = []
    for user in users:
         foodtype.append(user.foodtype)
         sum.append(user.sum)
    user_dict = {}
    user_dict['foodtype'] = foodtype
    user_dict['sum'] = sum
    return JsonResponse(user_dict)

# 读取性别
def sex(request):
    users = sex_model.objects.all()
    sex = []
    sum = []
    for user in users:
         sex.append(user.sex)
         sum.append(user.sum)
    user_dict = {}
    user_dict['sex'] = sex
    user_dict['sum'] = sum
    return JsonResponse(user_dict)

# 读取喜爱程度
def fav(request):
    users = fav_model.objects.all()
    fav = []
    sum = []
    for user in users:
         fav.append(user.fav)
         sum.append(user.sum)
    user_dict = {}
    user_dict['fav'] = fav
    user_dict['sum'] = sum
    return JsonResponse(user_dict)

# 读取不同食品在喜爱程度
def foodtype_fav(request):
    users = foodtype_fav_model.objects.all()
    foodtype = []
    fav = []
    sum = []
    for user in users:
         foodtype.append(user.foodtype)
         fav.append(user.fav)
         sum.append(user.sum)
    user_dict = {}
    user_dict['foodtype'] = foodtype
    user_dict['fav'] = fav
    user_dict['sum'] = sum
    return JsonResponse(user_dict)

# 读取不同食品在各性别的数据
def foodtype_sex(request):
    users = foodtype_sex_model.objects.all()
    foodtype = []
    sex = []
    sum = []
    for user in users:
         foodtype.append(user.foodtype)
         sex.append(user.ForM)
         sum.append(user.sum)
    user_dict = {}
    user_dict['foodtype'] = foodtype
    user_dict['sex'] = sex
    user_dict['sum'] = sum
    return JsonResponse(user_dict)

# 读取不同食品的年龄
def foodtype_age(request):
    users = foodtype_age_model.objects.all()
    foodtype = []
    age = []
    sum = []
    for user in users:
         foodtype.append(user.foodtype)
         age.append(user.age)
         sum.append(user.sum)
    user_dict = {}
    user_dict['foodtype'] = foodtype
    user_dict['age'] = age
    user_dict['sum'] = sum
    print(user_dict)
    return JsonResponse(user_dict)

2.Urls.py——路由:设置项目启动后的路由地址

1.导入所需库

from django.conf.urls import url
from . import views

2.编写URL

urlpatterns = [
    # user
    url(r'^index/1$', views.index,name='index'),
    url(r'^index/add$', views.add,name='add'),
    url(r'^index/insert$', views.insert,name='insert'),
    url(r'^index/delete/(?P[0-9]+)$', views.delete,name='delete'),
    url(r'^index/edit/(?P[0-9]+)$', views.edit,name='edit'),
    url(r'^index/update$', views.update,name='update'),
    url(r'^index/(?P[0-9]+)$', views.index_fen,name='index_fen'),

    # 登录操作
    url(r'^loging$',views.loging,name='login_admin'),
    url(r'^dologin$',views.dologin,name='dologin_admin'),
    url(r'^addlogin_admin$',views.addlogin_admin,name='addlogin_admin_admin'),
    url(r'^addlogin$',views.addlogin,name='addlogin_admin'),
    url(r'^logout$',views.logout,name='logout_admin'),

    # 前端页面
    url(r'^index_age$',views.index_age,name='index_age'),
    url(r'^index_sex$',views.index_sex,name='index_sex'),
    url(r'^index_fav$',views.index_fav,name='index_fav'),
    url(r'^index_foodtype$',views.index_foodtype,name='index_foodtype'),
    url(r'^index_foodtype_age$',views.index_foodtype_age,name='index_foodtype_age'),
    url(r'^index_foodtype_sex$',views.index_foodtype_sex,name='index_foodtype_sex'),
    url(r'^index_foodtype_fav$',views.index_foodtype_fav,name='index_foodtype_fav'),

    # 读取数据视图函数
    url(r'age/',views.age,name='age'),
    url(r'sex/',views.sex,name='sex'),
    url(r'foodtype/',views.foodtype,name='foodtype'),
    url(r'fav/',views.fav,name='fav'),
    url(r'foodtype_age/',views.foodtype_age,name='foodtype_age'),
    url(r'foodtype_sex/',views.foodtype_sex,name='foodtype_sex'),
    url(r'foodtype_fav/',views.foodtype_fav,name='foodtype_fav'),
]

3.settings.py——项目配置文件,项目中的所有功能都需要在该文件中进行配置

在Settings.py文件中需要修改如下代码:

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'myapp', ## 添加项目名字myapp
]
## 配置数据库连接
DATABASES = {
    'default': {
    'ENGINE': 'django.db.backends.mysql',
    'NAME': 'mytest', # 数据库名字
    'USER': 'root', #
    'PASSWORD': 'root',
    'HOST': 'localhost',
    'PORT': '3306',
    }
}
## 配置静态文件存储的文件夹路径
STATICFILES_DIRS=[
    os.path.join(BASE_DIR,'static')
]

4.Models.py——模型:定义数据库的映射类,每个类关联一张数据表,实现持久化,即MVT里面的模型

1.引入库

from django.db import models
from datetime import datetime

2.编写代码建立模型与数据库中的表进行连接

# age
class age_1_model(models.Model):
    age = models.IntegerField(default=None) ## 与数据库中的字段一致
    sum = models.IntegerField(default=None) 
    def toage(self):
        return {'age':self.age,'sum':self.sum}
    class Meta:
        db_table = "age" ## 设置读取数据库中的表名(必须设置,不然会读取django默认的数据库表名)

# sex
class sex_model(models.Model):
    sex = models.CharField(max_length=32)
    sum = models.IntegerField(default=None)
    def toage(self):
        return {'sex':self.sex,'sum':self.sum}
    class Meta:
        db_table = "sex"


# fav
class fav_model(models.Model):
    fav = models.CharField(max_length=32)
    sum = models.IntegerField(default=None)
    def toage(self):
        return {'fav':self.fav,'sum':self.sum}
    class Meta:
        db_table = "fav"


# foodtype
class foodtype_model(models.Model):
    foodtype = models.CharField(max_length=32)
    sum = models.IntegerField(default=None)
    def toage(self):
        return {'foodtype':self.foodtype,'sum':self.sum}
    class Meta:
        db_table = "foodtype"

# foodtype_age
class foodtype_age_model(models.Model):
    foodtype = models.CharField(max_length=32)
    age = models.IntegerField(default=None)
    sum = models.IntegerField(default=None)
    def tofoodtype_age(self):
        return ({'foodtype':self.foodtype,'age':self.age,'sum':self.sum})
    class Meta:
        db_table = "foodtype_age"

# foodtype_sex
class foodtype_sex_model(models.Model):
    foodtype = models.CharField(max_length=32)
    sex = models.IntegerField(default=None)
    sum = models.IntegerField(default=None)
    def tofoodtype_sex(self):
        return ({'foodtype':self.foodtype,'sex':self.sex,'sum':self.sum})
    class Meta:
        db_table = "foodtype_sex"

# foodtype_fav
class foodtype_fav_model(models.Model):
    foodtype = models.CharField(max_length=32)
    fav = models.IntegerField(default=None)
    sum = models.IntegerField(default=None)
    def tofoodtype_fav(self):
        return ({'foodtype':self.foodtype,'fav':self.fav,'sum':self.sum})
    class Meta:
        db_table = "foodtype_fav"

# loging
class login_model(models.Model):
    username = models.CharField(max_length=32)
    name = models.CharField(max_length=16)
    password = models.CharField(max_length=32)
    sex = models.IntegerField(default=1)
    address = models.CharField(max_length=255)
    code = models.CharField(max_length=6)
    phone = models.CharField(max_length=16)
    email = models.CharField(max_length=50)
    state = models.IntegerField(default=1)
    addtime = models.DateTimeField(default=datetime.now)
    def toDict(self):
        return {'username':self.username,'name':self.name,'password':self.password,'address':self.address,'phone':self.phone,'email':self.email,'state':self.state,'addtime':self.addtime}
    class Meta:
        db_table = "login"

# 用户

class user_model(models.Model):
    foodtype = models.CharField(max_length=32)
    sex = models.CharField(max_length=32)
    age = models.IntegerField(default=None)
    fav = models.CharField(max_length=32)
    def to(self):
        return {'foodtype':self.foodtype,'sex':self.sex,'age':self.age,'fav':self.fav}
    class Meta:
        db_table = "demo"

二、HTML模板

django+mysql+echarts实现数据可视化到前端_第2张图片

1.addlogin.html

代码如下:

DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>管理员注册title>
    <style>
* {
            padding: 0;
            margin: 0;
        }
        html {
            height: 100%;
        }
        body {
            background-image: linear-gradient(to bottom right, #1abc9c, rgb(130, 88, 186));
        }
        .login-container {
            width: 600px;
            height: 315px;
            margin: 0 auto;
            margin-top: 10%;
            border-radius: 15px;
            box-shadow: 0 10px 50px 0px rbg(59, 45, 159);
            background-image: linear-gradient(to bottom right, #1abc9c, rgb(92, 103, 211));
        }
        .left-container {
            display: inline-block;
            width: 330px;
            border-top-left-radius: 15px;
            border-bottom-left-radius: 15px;
            padding: 60px;
            background-image: linear-gradient(to bottom right, #1abc9c, rgb(92, 103, 211));
        }
        .title {
            color: #fff;
            font-size: 18px;
            font-weight: 200;
        }
        .title span {
            border-bottom: 3px solid rgb(237, 221, 22);
        }
        .input-container {
            padding: 20px 0;
        }
        input {
            border: 0;
            background: none;
            outline: none;
            color: #fff;
            margin: 20px 0;
            display: block;
            width: 100%;
            padding: 5px 0;
            transition: .2s;
            border-bottom: 1px solid rgb(199, 191, 219);
        }
        input:hover {
            border-bottom-color: #fff;
        }
        ::-webkit-input-placeholder {
            color: rgb(199, 191, 219);
        }
        .message-container {
            font-size: 14px;
            transition: .2s;
            color: rgb(199, 191, 219);
            cursor: pointer;
        }
        .message-container:hover {
            color: #fff;
        }
        .right-container {
            width: 145px;
            display: inline-block;
            height: calc(100% - 120px);
            vertical-align: top;
            padding: 60px 0;
        }
        .regist-container {
            text-align: center;
            color: #fff;
            font-size: 18px;
            font-weight: 200;
        }
        .regist-container span {
            border-bottom: 3px solid rgb(237, 221, 22);
        }
        .action-container {
            font-size: 10px;
            color: #fff;
            text-align: center;
            position: relative;
            top: 200px;
        }
        .action-container span {
            border: 1px solid rgb(237, 221, 22);
            padding: 10px;
            display: inline;
            line-height: 20px;
            border-radius: 20px;
            position: absolute;
            bottom: 10px;
            left: calc(72px - 20px);
            transition: .2s;
            cursor: pointer;
        }
        .action-container span:hover {
            background-color: rgb(237, 221, 22);
            color: rgb(95, 76, 194);
        }
        .mya{
            text-decoration: none;
            padding: 10px 10px;
            background-image: linear-gradient(to bottom right, #1abc9c, rgb(92, 103, 211));
            color:#fff;
            border-radius: 6px;
        }
    style>
head>
<body>
    <div class="login-container">
      <form action="{% url 'addlogin_admin' %}" method="post">
			{% csrf_token %}
        <div class="left-container">
            <div class="input-container">
                <input type="text" name="name" placeholder="用户名">
                <input type="password" name="password" placeholder="密码">
                <input type="state" name="state" placeholder="是否为管理员">
            div>
        div>
		<div><input type="submit" value="注册" class="mya">div>
		form>
    div>
body>
html>

2.login

DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>管理员登录title>
    <style>
        * {
            padding: 0;
            margin: 0;
        }
        html {
            height: 100%;
        }
        body {
            background-image: linear-gradient(to bottom right, #1abc9c, rgb(130, 88, 186));
        }
        .login-container {
            width: 600px;
            height: 315px;
            margin: 0 auto;
            margin-top: 10%;
            border-radius: 15px;
            box-shadow: 0 10px 50px 0px rbg(59, 45, 159);
            background-image: linear-gradient(to bottom right, #1abc9c, rgb(92, 103, 211));
        }
        .left-container {
            display: inline-block;
            width: 330px;
            border-top-left-radius: 15px;
            border-bottom-left-radius: 15px;
            padding: 60px;
            background-image: linear-gradient(to bottom right, #1abc9c, rgb(92, 103, 211));
        }
        .title {
            color: #fff;
            font-size: 18px;
            font-weight: 200;
        }
        .title span {
            border-bottom: 3px solid rgb(237, 221, 22);
        }
        .input-container {
            padding: 20px 0;
        }
        input {
            border: 0;
            background: none;
            outline: none;
            color: #fff;
            margin: 20px 0;
            display: block;
            width: 100%;
            padding: 5px 0;
            transition: .2s;
            border-bottom: 1px solid rgb(199, 191, 219);
        }
        input:hover {
            border-bottom-color: #fff;
        }
        ::-webkit-input-placeholder {
            color: rgb(199, 191, 219);
        }
        .message-container {
            font-size: 14px;
            transition: .2s;
            color: rgb(199, 191, 219);
            cursor: pointer;
        }
        .message-container:hover {
            color: #fff;
        }
        .right-container {
            width: 145px;
            display: inline-block;
            height: calc(100% - 120px);
            vertical-align: top;
            padding: 60px 0;
        }
        .regist-container {
            text-align: center;
            color: #fff;
            font-size: 18px;
            font-weight: 200;
        }
        .regist-container span {
            border-bottom: 3px solid rgb(237, 221, 22);
        }
        .action-container {
            font-size: 10px;
            color: #fff;
            text-align: center;
            position: relative;
            top: 200px;
        }
        .action-container span {
            border: 1px solid rgb(237, 221, 22);
            padding: 10px;
            display: inline;
            line-height: 20px;
            border-radius: 20px;
            position: absolute;
            bottom: 10px;
            left: calc(72px - 20px);
            transition: .2s;
            cursor: pointer;
        }
        .action-container span:hover {
            background-color: rgb(237, 221, 22);
            color: rgb(95, 76, 194);
        }
        .mya{
            text-decoration: none;
            padding: 10px 10px;
            background-image: linear-gradient(to bottom right, #1abc9c, rgb(92, 103, 211));
            color:#fff;
            border-radius: 6px;
        }
    style>
head>
<body>
    <div class="login-container">
		<form action = "{% url 'dologin_admin' %}" method="post">
			{% csrf_token %}
        <div class="left-container">
            <div class="input-container">
                <input type="text" name="username" placeholder="用户名">
                <input type="password" name="userpwd" placeholder="密码">
            div>
        div>
		<div>
            <a href="{% url 'addlogin_admin_admin' %}" class="mya" style="width:600px;">注册a>
            <input type="submit" value="登录" class="mya">
        div>
		form>
    div>
body>
html>



总结

文件内容太多,不想写了。
需要自取,网盘链接:

你可能感兴趣的:(Python从零开始,前端,django,mysql,python)