基于django的可视化大屏编程

一、创建工程

基于django的可视化大屏编程_第1张图片 1、在项目下创建模板static目录,并建立cssimgjs目录

基于django的可视化大屏编程_第2张图片

 基于django的可视化大屏编程_第3张图片

基于django的可视化大屏编程_第4张图片

 2、js目录下创建charts目录,其下创建bar.jsbar_vertical.jsheatmap.jsline.jsmap.jspie.jsrose.jssandian.js、wordcloud.js文件

基于django的可视化大屏编程_第5张图片

 wordcloud.js的代码

function create_wordcloud(dom_id,data) {
    var chart = echarts.init(document.getElementById(dom_id));
    var option = {
      tooltip: {},
      series: [{
        type: 'wordCloud',
        gridSize: 2,
        sizeRange: [12, 50],
        rotationRange: [-90, 90],
        //shape: 'pentagon',
        width:100,
        height: 100,
        drawOutOfBound: true,
        textStyle: {
          normal: {
            color: function () {
              return 'rgb(' + [
                Math.round(Math.random() * 160),
                Math.round(Math.random() * 160),
                Math.round(Math.random() * 160)
              ].join(',') + ')';
            }
          },
          emphasis: {
            shadowBlur: 10,
            shadowColor: '#333'
          }
        },
        data: data
      }]
    };

    if (option && typeof option === "object") {
        chart.setOption(option, true);
    }
  }

 dashboard.html文件




    
        
        
        用户行为分析展示大屏
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        

    
    
        
用户购物行为分析展示大屏
用户性别分析
新用户注册
商品推荐排行
用户地域分布
商品热销词云
商品销售量分布
用户等级分布
用户活跃度热图
商品品牌排行

 models.py文件

from django.db import models

# Create your models here.


class attribute(models.Model):
    id = models.IntegerField(verbose_name="信息ID", default=1, primary_key=True, unique=True, null=False)
    type = models.IntegerField(verbose_name="类型", default=1, blank=False, null=False)
    attr = models.CharField(verbose_name="属性罗列", max_length=50, null=False, default='')
    value = models.CharField(verbose_name="占比罗列", max_length=50, null=False, default='')
    operator = models.IntegerField(verbose_name="操作人员ID", default=999999, null=False)
    opertime = models.DateField(verbose_name="操作时间", max_length=50, null=False)

class action(models.Model):
    id = models.IntegerField(verbose_name="信息ID",default=1, primary_key=True, unique=True, null=False)
    action = models.CharField(verbose_name="行为大类", max_length=50, null=False, default='')
    quantity = models.CharField(verbose_name="数量占比", max_length=50, null=False, default='')
    operator = models.IntegerField(verbose_name="操作人员ID", default=999999, null=False)
    opertime = models.DateField(verbose_name="操作时间", max_length=50, null=False)

 创建view.py文件

from django.http import HttpResponse
from django.shortcuts import render
from user.models import attribute as UserAttribute
from user.models import action as UserAction
from product.models import attribute as ProductAttribute
from product.models import action as ProductAction
import json
from enum import Enum

class UserAttrType(Enum):
    gender = 1
    province = 2
    viplevel = 3
    registertime = 4

class ProductAttrType(Enum):
    category = 1
    brand= 2
    tradename = 3

def get_user_gender():

    user_gender = UserAttribute.objects.filter(type=1).latest('id')
    return user_gender

def get_user_province():

    user_province = UserAttribute.objects.filter(type=2).latest('id')
    return user_province

def get_user_viplevel():

    user_viplevel = UserAttribute.objects.filter(type=3).latest('id')
    return user_viplevel

def get_user_registertime():

    user_registertime = UserAttribute.objects.filter(type=4).latest('id')
    return user_registertime

def get_user_action(request):

    product_info = UserAction.objects.latest('id')
    return product_info

def get_product_attribute(request):

    user_info = ProductAttribute.objects.latest('id')
    return user_info

def get_product_name():

    product_name = ProductAttribute.objects.filter(type=3).latest('id')
    return product_name

def get_product_brand():

    product_brand = ProductAttribute.objects.filter(type=2).latest('id')
    return product_brand

def get_product_category():

    product_category = ProductAttribute.objects.filter(type=1).latest('id')
    return product_category

def get_prodcut_action(request):

    product_info = ProductAction.objects.latest('id')
    return product_info

def get_user_gender_json(request):
    user_gender=get_user_gender()
    resp = {}
    resp['errorcode'] = 100
    resp['detail'] = "success"
    data = []

    try:
        for i in range(len(user_gender.attr.split( '|'))):
            data.append({"name": user_gender.attr.split( '|')[i], "value": user_gender.value.split( '|')[i]})
    except Exception as e:
        print('Error:', e)
        resp['errorcode'] = 404
        resp['detail'] = "failure"
        data = e

    resp['data'] =data

    return HttpResponse(json.dumps(resp,ensure_ascii=False), content_type="application/json")


def get_user_province_json(request):
    user_province=get_user_province()
    resp = {}
    resp['errorcode'] = 100
    resp['detail'] = "success"
    data =[]

    try:
        for i in range(len(user_province.attr.split( '|'))):
            data.append({"name": user_province.attr.split( '|')[i], "value": user_province.value.split( '|')[i]})
    except Exception as e:
        print('Error:', e)
        resp['errorcode'] = 404
        resp['detail'] = "failure"
        data = e

    resp['data'] =data

    return HttpResponse(json.dumps(resp,ensure_ascii=False), content_type="application/json")


def get_user_viplevel_json(request):
    user_viplevel=get_user_viplevel()
    resp = {}
    resp['errorcode'] = 100
    resp['detail'] = "success"
    data =[]

    try:
        for i in range(len(user_viplevel.attr.split( '|'))):
            data.append({"name": user_viplevel.attr.split( '|')[i], "value": user_viplevel.value.split( '|')[i]})
    except Exception as e:
        print('Error:', e)
        resp['errorcode'] = 404
        resp['detail'] = "failure"
        data = e

    resp['data'] =data

    return HttpResponse(json.dumps(resp,ensure_ascii=False), content_type="application/json")

def get_user_registertime_json(request):
    user_registertime=get_user_registertime()
    resp = {}
    resp['errorcode'] = 100
    resp['detail'] = "success"
    data =[]

    try:
        for i in range(len(user_registertime.attr.split( '|'))):
            data.append({"name": user_registertime.attr.split( '|')[i], "value": user_registertime.value.split( '|')[i]})
    except Exception as e:
        print('Error:', e)
        resp['errorcode'] = 404
        resp['detail'] = "failure"
        data = e

    resp['data'] =data

    return HttpResponse(json.dumps(resp,ensure_ascii=False), content_type="application/json")


def get_product_category_json(request):
    product_category=get_product_category()
    resp = {}
    resp['errorcode'] = 100
    resp['detail'] = "success"
    data =[]

    try:
        for i in range(len(product_category.attr.split( '|'))):
            data.append({"name": product_category.attr.split( '|')[i], "value": product_category.value.split( '|')[i]})
    except Exception as e:
        print('Error:', e)
        resp['errorcode'] = 404
        resp['detail'] = "failure"
        data = e

    resp['data'] =data

    return HttpResponse(json.dumps(resp,ensure_ascii=False), content_type="application/json")

def get_product_brand_json(request):
    product_brand=get_product_brand()
    resp = {}
    resp['errorcode'] = 100
    resp['detail'] = "success"
    data =[]

    try:
        for i in range(len(product_brand.attr.split( '|'))):
            data.append({"name": product_brand.attr.split( '|')[i], "value": product_brand.value.split( '|')[i]})
    except Exception as e:
        print('Error:', e)
        resp['errorcode'] = 404
        resp['detail'] = "failure"
        data = e

    resp['data'] =data

    return HttpResponse(json.dumps(resp,ensure_ascii=False), content_type="application/json")

def get_product_name_json(request):
    product_name=get_product_name()
    resp = {}
    resp['errorcode'] = 100
    resp['detail'] = "success"
    data =[]

    try:
        for i in range(len(product_name.attr.split( '|'))):
            data.append({"name": product_name.attr.split( '|')[i], "value": product_name.value.split( '|')[i]})
    except Exception as e:
        print('Error:', e)
        resp['errorcode'] = 404
        resp['detail'] = "failure"
        data = e

    resp['data'] =data

    return HttpResponse(json.dumps(resp,ensure_ascii=False), content_type="application/json")

def dashboard(request,):
        return render(request,'dashboard.html')

 修改urls.py文件

"""ConsumerBuyingBehaviour URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/2.2/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  path('', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.urls import include, path
    2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path
from django.conf.urls import url
from . import view

urlpatterns = [
    path('',view.dashboard),
    path('api/user_gender/', view.get_user_gender_json),
    path('api/user_province/', view.get_user_province_json),
    path('api/user_viplevel/', view.get_user_viplevel_json),
    path('api/user_registertime/', view.get_user_registertime_json),
    path('api/product_category/', view.get_product_category_json),
    path('api/product_brand/', view.get_product_brand_json),
    path('api/product_name/', view.get_product_name_json),
    path('dashboard/', view.dashboard),
]

修改settings.py文件

"""
Django settings for ConsumerBuyingBehaviour project.

Generated by 'django-admin startproject' using Django 2.2.4.

For more information on this file, see
https://docs.djangoproject.com/en/2.2/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.2/ref/settings/
"""

import os

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))


# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '0=$&m8he4kttcw8xzw534olj-m%-vud%%cdtz)_#vo+l_oumht'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = ['*']


# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'user',
    'product',
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'ConsumerBuyingBehaviour.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [BASE_DIR+"/templates"],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'ConsumerBuyingBehaviour.wsgi.application'


# Database
# https://docs.djangoproject.com/en/2.2/ref/settings/#databases

DATABASES = {
    'default': {
        #'ENGINE': 'django.db.backends.sqlite3',
        #'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
        'ENGINE': 'django.db.backends.mysql',
        #'NAME': 'consumer_buying_behaviour',
        #'USER': 'user01',
        #'PASSWORD': 'sugon123!',
        #'HOST': 'localhost',
        #'PORT': '3306',,
        'NAME': 'user_actions_db',
        'USER': 'root',
        'PASSWORD': '123456',
        'HOST': '211.84.112.23',
        'PORT': '8046',
        #'HOST': '172.16.0.11',
        #'PORT': '3306',
    }
}


# Password validation
# https://docs.djangoproject.com/en/2.2/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]


# Internationalization
# https://docs.djangoproject.com/en/2.2/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.2/howto/static-files/

STATIC_URL = '/static/'
STATICFILES_DIRS=[os.path.join(BASE_DIR,'static'),]

3、发布工程

python.exe manage.py runserver 127.0.0.1:8000

你可能感兴趣的:(基于django的可视化大屏编程)