饮冰三年-人工智能-Python-33博客园山寨版之报障管理

报障单的内容和其实和文章管理内容类似

1:创建数据模型

class Trouble(models.Model):
    '''报障单'''
    uuid = models.UUIDField(primary_key=True,auto_created=True, default=uuid.uuid4, editable=False)
    title = models.CharField(verbose_name="报障标题", max_length=1000)
    detail = models.TextField(verbose_name='报障详情')
    reportUser = models.ForeignKey(verbose_name='报修人', to="UserInfo", to_field="uid", related_name="reportUsers",
                                   on_delete=models.CASCADE, null=True)
    processUser = models.ForeignKey(verbose_name='处理人', to="UserInfo", to_field="uid", related_name="processUsers",
                                    on_delete=models.CASCADE, null=True)
    processSolution = models.TextField(verbose_name='处理方法',null=True)
    createTime = models.DateTimeField(verbose_name='创建时间', auto_now_add=True)
    processTime = models.DateTimeField(verbose_name='处理时间', auto_now_add=True)
    type_status = [
        (0, '已删除'),
        (1, '待处理'),
        (2, '处理中'),
        (3, '已处理'),
    ]
    pj_choices = (
        (1, '不满意'),
        (2, '一般'),
        (3, '很好'),
    )
    status = models.IntegerField(choices=type_status, default=1)
    evaluate = models.IntegerField(choices=pj_choices, null=True, default=2)
models.py

2:url设置

from django.conf.urls import url
from django.conf.urls import include
from .views import user,trouble

urlpatterns = [
    url(r'^index.html$', user.index),
    url(r'article-(?P<ms_Type>\d+)-(?P<classification_id>\d+).html$', user.article, name='article'),
    url(r'^add-article.html$',user.add_article),  #创建文章路由
    url(r'^del-article-(?P<nid>\d+).html$', user.del_article),#删除文章路由
    url(r'^edit-article-(?P<nid>\d+).html$', user.edit_article),#修改文章路由

    # 一般用户: 提交报障单,查看,修改(未处理),评分(处理完成,未评分)
    url(r'^trouble-list.html$', trouble.trouble_list),
    url(r'^trouble-create.html$', trouble.trouble_create),
    url(r'^trouble-edit-([a-zA-Z0-9-]+).html$', trouble.trouble_edit),

]
urls.py

3:Form表单

# 引入文件
from django import forms
from django.forms import fields
from django.forms import widgets
from  repository import models

class TroubleForm(forms.Form):
    title = fields.CharField(
        max_length=32,
        widget=widgets.TextInput(attrs={'class': 'form-control', 'placeholder': '报障单标题'})
    )
    detail = fields.CharField(
        widget=widgets.Textarea(attrs={'id': 'detail', 'class': 'kind-content'})
    )
Form/trouble.py

4:增删操作。View设置后台逻辑

from django.shortcuts import render,redirect,HttpResponse
from repository import models
from forms.trouble import TroubleForm  #引用form中的文章表单,用于添加、修改文章
import datetime #引入时间模块
def trouble_list(request):
    # user_info = request.session.get('user_info') # {id:'',}
    current_user_id = request.session['user_info']['uid']
    result = models.Trouble.objects.filter(reportUser_id=current_user_id).order_by('status').\
        only('uuid','title','status','createTime','processUser')
    return render(request,'Backend/backend_trouble_list.html',{'result': result})

def trouble_create(request):
    if request.method == 'GET':
        form = TroubleForm()
    else:
        form = TroubleForm(request.POST)
        if form.is_valid():
            dic = {}
            dic['reportUser_id'] = request.session['user_info']['uid'] # session中获取
            dic['createTime'] = datetime.datetime.now()
            dic['status'] = 1
            dic.update(form.cleaned_data)
            models.Trouble.objects.create(**dic)
            return redirect('/backend/trouble-list.html')
    return render(request, 'Backend/backend_trouble_create.html',{'form':form})

def trouble_edit(request,uuid):
    if request.method == "GET":
        obj = models.Trouble.objects.filter(uuid=uuid, status=1).only('uuid', 'title', 'detail').first()
        if not obj:
            return HttpResponse('已处理中的保单章无法修改..')
        # initial 仅初始化
        form = TroubleForm(initial={'title': obj.title,'detail': obj.detail,'uuid':obj.uuid})
        # 执行error会进行验证
        return render(request,'Backend/backend_trouble_edit.html',{'form':form,'uuid':uuid})
    else:
        form = TroubleForm(data=request.POST)
        if form.is_valid():
            # 受响应的行数
            v = models.Trouble.objects.filter(uuid=uuid, status=1).update(**form.cleaned_data)
            if not v:
                return HttpResponse('已经被处理')
            else:
                return redirect('/backend/trouble-list.html')
        return render(request, 'Backend/backend_trouble_edit.html', {'form': form,'uuid':uuid})
trouble.py

5:前台页面

5.1列表页面

{% extends 'Backend/backend_layout.html' %}

{% block conent %}
    <ol class="breadcrumb" style="margin-bottom: 0;">
        <li><a href="#">保障管理</a></li>
        <li class="active">保障列表</li>
    </ol>
    <div>

        <div class="clearfix"  style="height: 36px;line-height: 35px;padding: 0 15px;border-top: 1px solid #dddddd;background-color: #f1f0f0">
            <i class="fa fa-table" aria-hidden="true"></i>
            <a target="_blank" href="/backend/trouble-create.html" class="right"
               style="display: inline-block;padding:0 10px;background-color: #428bca;color: #ffffff;">
                <i class="fa fa-plus-circle" aria-hidden="true"></i>
                创建报障单
            </a>
        </div>

        <table class="table table-bordered">
            <thead>
            <tr>
                <th>保障标题</th>
                <th>状态</th>
                <th>创建时间</th>
                <th>处理人</th>
                <th>操作</th>
            </tr>
            </thead>
            <tbody>
            {% for row in result %}
                <tr>
                    <td>{{ row.title }}</td>
                    <td>{{ row.get_status_display }}</td>
                    <td>{{ row.createTime }}</td>
                    <td>{{ row.processUser.username }}</td>
                    <td>
                        <a class="btn btn-danger btn-xs">
                            <i class="fa fa-times" aria-hidden="true"></i>
                            删除
                        </a>
                        |
                        <a class="btn btn-primary btn-xs" href="/backend/trouble-edit-{{ row.uuid }}.html">
                            <i class="fa fa-pencil-square-o" aria-hidden="true"></i>
                            编辑
                        </a>
                    </td>
                </tr>
            {% endfor %}

            </tbody>
        </table>
        <div class="clearfix">
            <ul class="pagination right" style="margin-top: 0">
               {{ page_str }}
            </ul>
        </div>
    </div>


{% endblock %}

{% block js %}

{% endblock %}
backend_trouble_list.html

5.2 新增页面

{% extends 'Backend/backend_layout.html' %}

{% block css %}
    <link rel="stylesheet" href="/static/plugins/kindeditor/themes/default/default.css"/>
    <style>
        .kind-content {
            width: 100%;
            min-height: 500px;
        }
    </style>
{% endblock %}

{% block conent %}
    <ol class="breadcrumb" style="margin-bottom: 0;">
        <li><a href="#">保障管理</a></li>
        <li class="active">创建报障单</li>
    </ol>
    <div style="padding: 5px 8px;">
        <form method="POST" action="/backend/trouble-create.html" novalidate>
            {% csrf_token %}
            <div class="form-group">
                <label for="{{ form.title.id_for_label }}">标题 <span>{{ form.title.errors.0 }}</span></label>
                {{ form.title }}
            </div>
            <div class="form-group">
                <label for="detail">内容 <span>{{ form.detail.errors.0 }}</span></label>
                {{ form.detail }}
            </div>

            <div class="form-group">
                <input type="submit" class="btn btn-primary" value="保 存">
            </div>
        </form>
    </div>


{% endblock %}

{% block js %}
    <script charset="utf-8" src="/static/plugins/kindeditor/kindeditor-all-min.js"></script>
    <script charset="utf-8" src="/static/plugins/kindeditor/lang/zh-CN.js"></script>
    <script>
        KindEditor.ready(function (K) {
            var editor = K.create('#detail', {
                resizeType: 1
            });
        });
    </script>
{% endblock %}
backend_trouble_create.html

5.3 编辑页面

{% extends 'Backend/backend_layout.html' %}

{% block css %}
    <link rel="stylesheet" href="/static/plugins/kindeditor/themes/default/default.css"/>
    <style>
        .kind-content {
            width: 100%;
            min-height: 500px;
        }
    </style>
{% endblock %}

{% block conent %}
    <ol class="breadcrumb" style="margin-bottom: 0;">
        <li><a href="#">保障管理</a></li>
        <li class="active">修改报障单</li>
    </ol>
    <div style="padding: 5px 8px;">
        <form method="POST" action="/backend/trouble-edit-{{ uuid }}.html" novalidate>
            {% csrf_token %}
            <div class="form-group">
                <label for="{{ form.title.id_for_label }}">标题 <span>{{ form.title.errors.0 }}</span></label>
                {{ form.title }}
            </div>
            <div class="form-group">
                <label for="detail">内容 <span>{{ form.detail.errors.0 }}</span></label>
                {{ form.detail }}
            </div>

            <div class="form-group">
                <input type="submit" class="btn btn-primary" value="保 存">
            </div>
        </form>
    </div>


{% endblock %}

{% block js %}
    <script charset="utf-8" src="/static/plugins/kindeditor/kindeditor-all-min.js"></script>
    <script charset="utf-8" src="/static/plugins/kindeditor/lang/zh-CN.js"></script>
    <script>
        KindEditor.ready(function (K) {
            var editor = K.create('#detail', {
                resizeType: 1
            });
        });
    </script>
{% endblock %}
backend_trouble_edit.html

 6:处理报障单

6.1 url补充

from django.conf.urls import url
from django.conf.urls import include
from .views import user,trouble

urlpatterns = [
    url(r'^index.html$', user.index),
    url(r'article-(?P<ms_Type>\d+)-(?P<classification_id>\d+).html$', user.article, name='article'),
    url(r'^add-article.html$',user.add_article),  #创建文章路由
    url(r'^del-article-(?P<nid>\d+).html$', user.del_article),#删除文章路由
    url(r'^edit-article-(?P<nid>\d+).html$', user.edit_article),#修改文章路由

    # 一般用户: 提交报障单,查看,修改(未处理),评分(处理完成,未评分)
    url(r'^trouble-list.html$', trouble.trouble_list),
    url(r'^trouble-create.html$', trouble.trouble_create),
    url(r'^trouble-edit-([a-zA-Z0-9-]+).html$', trouble.trouble_edit),
    # 工程师: 处理报障单(未被接单的报障单+已经处理过的报障单)
    url(r'^trouble-kill-list.html$', trouble.trouble_kill_list),
    url(r'^trouble-kill-(?P<uuid>[a-zA-Z0-9-]+).html$', trouble.trouble_kill),
    url(r'^ajaxGetResolveDetail.html$', trouble.getResolveDetail), #通过nid获取解决方案
]
url补充

6.2 实体类的完善(常见故障类型)

from django.db import models
import uuid

# Create your models here.
class UserInfo(models.Model):
    '''用户表'''
    uid = models.BigAutoField(primary_key=True)
    username = models.CharField(verbose_name="用户名", max_length=64, unique=True)
    pwd = models.CharField(verbose_name='密码', max_length=64)
    email = models.EmailField(verbose_name='邮箱', unique=True)
    img = models.ImageField(verbose_name='头像', null=True)
    status=models.IntegerField(verbose_name='状态',default=1,null=False)

class BlogInfo(models.Model):
    '''博客信息'''
    bid = models.BigAutoField(primary_key=True)
    surfix = models.CharField(verbose_name='博客后缀名', max_length=64)
    theme = models.CharField(verbose_name='博客主题', max_length=64)
    title = models.CharField(verbose_name='博客标题', max_length=1000)
    summary = models.CharField(verbose_name='博客简介', max_length=1000)
    user = models.OneToOneField(to="UserInfo", to_field="uid", on_delete=models.CASCADE, null=True)
    status = models.IntegerField(verbose_name='状态', default=1, null=False)

class UserFans(models.Model):
    '''互粉表'''
    starUser = models.ForeignKey(verbose_name='博主', to="UserInfo", to_field="uid", related_name="starUsers",
                                 on_delete=models.CASCADE, null=True)
    fansUser = models.ForeignKey(verbose_name='粉丝', to="UserInfo", to_field="uid", related_name='fansUsers',
                                 on_delete=models.CASCADE, null=True)
    status = models.IntegerField(verbose_name='状态', default=1, null=False)
    class Meta:
        unique_together = [
            ('starUser', 'fansUser'),
        ]

class Trouble(models.Model):
    '''报障单'''
    uuid = models.UUIDField(primary_key=True,auto_created=True, default=uuid.uuid4, editable=False)
    title = models.CharField(verbose_name="报障标题", max_length=1000)
    detail = models.TextField(verbose_name='报障详情')
    reportUser = models.ForeignKey(verbose_name='报修人', to="UserInfo", to_field="uid", related_name="reportUsers",
                                   on_delete=models.CASCADE, null=True)
    processUser = models.ForeignKey(verbose_name='处理人', to="UserInfo", to_field="uid", related_name="processUsers",
                                    on_delete=models.CASCADE, null=True)
    processSolution = models.TextField(verbose_name='处理方法',null=True)
    createTime = models.DateTimeField(verbose_name='创建时间', auto_now_add=True)
    processTime = models.DateTimeField(verbose_name='处理时间', auto_now_add=True)
    type_status = [
        (0, '已删除'),
        (1, '待处理'),
        (2, '处理中'),
        (3, '已处理'),
    ]
    pj_choices = (
        (1, '不满意'),
        (2, '一般'),
        (3, '很好'),
    )
    status = models.IntegerField(choices=type_status, default=1)
    evaluate = models.IntegerField(choices=pj_choices, null=True, default=2)

class TroubleResolveType(models.Model):
    '''报障单--处理类型模板---'''
    nid = models.AutoField(primary_key=True)
    title = models.CharField(verbose_name="报障处理类型标题", max_length=1000)
    detail = models.TextField(verbose_name='详细处理内容')
    createUser = models.ForeignKey(verbose_name='处理人', to="UserInfo", to_field="uid", related_name="createUser",
                                 on_delete=models.CASCADE, null=True)
    status = models.IntegerField(verbose_name='状态', default=1, null=False)

class Tag(models.Model):
    nid = models.AutoField(primary_key=True)
    title = models.CharField(verbose_name='标签名称', max_length=32)
    blog = models.ForeignKey(verbose_name='所属博客', to='BlogInfo', to_field='bid', on_delete=models.CASCADE, null=True)
    status = models.IntegerField(verbose_name='状态', default=1, null=False)

class Classification(models.Model):
    nid = models.AutoField(primary_key=True)
    title = models.CharField(verbose_name='分类名称', max_length=32)
    blog = models.ForeignKey(verbose_name='所属博客', to='BlogInfo', to_field='bid', on_delete=models.CASCADE, null=True)


class Article(models.Model):
    nid = models.BigAutoField(primary_key=True)
    title = models.CharField(verbose_name='文章标题', max_length=128)
    summary = models.CharField(verbose_name='简介', max_length=256)
    blog = models.ForeignKey(verbose_name='所属博客', to='BlogInfo', to_field='bid', on_delete=models.CASCADE, null=True)
    create_time = models.DateTimeField(verbose_name='创建时间', null=False)
    read_count = models.IntegerField(verbose_name='阅读数量',default=0)
    comment_count = models.IntegerField(verbose_name='评论数量',default=0)
    up_count = models.IntegerField(verbose_name='点赞数量',default=0)
    down_count = models.IntegerField(verbose_name='踩数量',default=0)
    classification_id = models.ForeignKey(verbose_name='文章分类', to='Classification', to_field="nid",
                                          on_delete=models.CASCADE, null=True)
    masterStation_type = [
        (1, "Python"),
        (2, "Linux"),
        (3, "OpenStack"),
        (4, "GoLang"),
    ]
    ms_Type = models.IntegerField(verbose_name='主站分类', choices=masterStation_type, default=None)
    tags=models.ManyToManyField(
        to='Tag',
        through='Article_Tag',
        through_fields=('article_id','tag_id')
    )
    status = models.IntegerField(verbose_name='状态', default=1, null=False)
class Article_Detail(models.Model):
    detail = models.TextField(verbose_name='文章详细', max_length=models.Max)
    article_id = models.OneToOneField(verbose_name='文章id', to='Article', to_field='nid', on_delete=models.CASCADE,
                                      null=True)
    status = models.IntegerField(verbose_name='状态', default=1, null=False)

class Article_Tag(models.Model):
    # 文章标签分类
    article_id = models.ForeignKey(verbose_name='文章ID', to='Article', to_field='nid', on_delete=models.CASCADE,
                                   null=True)
    tag_id = models.ForeignKey(verbose_name='标签ID', to='Tag', to_field='nid', on_delete=models.CASCADE, null=True)
    class Meta:
        unique_together=[("article_id","tag_id")]

    status = models.IntegerField(verbose_name='状态', default=1, null=False)

class Article_upDown(models.Model):
    # 文章标签分类
    article_id = models.ForeignKey(verbose_name='文章ID', to='Article', to_field='nid', on_delete=models.CASCADE,
                                   null=True)
    user = models.ForeignKey(verbose_name='赞或踩用户', to='UserInfo', to_field='uid',on_delete=models.CASCADE, null=True)
    up = models.BooleanField(verbose_name='是否赞', default=True)
    status = models.IntegerField(verbose_name='状态', default=1, null=False)
    class Meta:
        unique_together = [
            ('article_id', 'user')
        ]


class Article_Comment(models.Model):
    '''评论表'''
    id = models.BigAutoField(verbose_name='评论ID', primary_key=True)
    user = models.ForeignKey(verbose_name='评论人', to='UserInfo', to_field='uid', on_delete=models.CASCADE, null=True)
    comment = models.CharField(verbose_name='评论内容', max_length=1000)
    createTime = models.DateTimeField(verbose_name='评论时间', auto_now_add=True)
    reply = models.ForeignKey(verbose_name='回复评论', to='self', related_name='back', on_delete=models.CASCADE, null=True)
    article = models.ForeignKey(verbose_name='评论文章', to='Article', to_field='nid',on_delete=models.CASCADE, null=True)
    status = models.IntegerField(verbose_name='状态', default=1, null=False)
实体类(报障单--处理类型模板---')

6.3 后台逻辑的完善

from django.shortcuts import render,redirect,HttpResponse
from repository import models
from forms.trouble import TroubleForm,TroubleKill  #引用form中的文章表单,用于添加、修改文章
from django.db.models import Q
import json
import datetime #引入时间模块
def trouble_list(request):
    # user_info = request.session.get('user_info') # {id:'',}
    current_user_id = request.session['user_info']['uid']
    result = models.Trouble.objects.filter(reportUser_id=current_user_id).order_by('status').\
        only('uuid','title','status','createTime','processUser')
    return render(request,'Backend/backend_trouble_list.html',{'result': result})

def trouble_create(request):
    if request.method == 'GET':
        form = TroubleForm()
    else:
        form = TroubleForm(request.POST)
        if form.is_valid():
            dic = {}
            dic['reportUser_id'] = request.session['user_info']['uid'] # session中获取
            dic['createTime'] = datetime.datetime.now()
            dic['status'] = 1
            dic.update(form.cleaned_data)
            models.Trouble.objects.create(**dic)
            return redirect('/backend/trouble-list.html')
    return render(request, 'Backend/backend_trouble_create.html',{'form':form})

def trouble_edit(request,uuid):
    if request.method == "GET":
        obj = models.Trouble.objects.filter(uuid=uuid, status=1).only('uuid', 'title', 'detail').first()
        if not obj:
            return HttpResponse('已处理中的保单章无法修改..')
        # initial 仅初始化
        form = TroubleForm(initial={'title': obj.title,'detail': obj.detail,'uuid':obj.uuid})
        # 执行error会进行验证
        return render(request,'Backend/backend_trouble_edit.html',{'form':form,'uuid':uuid})
    else:
        form = TroubleForm(data=request.POST)
        if form.is_valid():
            # 受响应的行数
            v = models.Trouble.objects.filter(uuid=uuid, status=1).update(**form.cleaned_data)
            if not v:
                return HttpResponse('已经被处理')
            else:
                return redirect('/backend/trouble-list.html')
        return render(request, 'Backend/backend_trouble_edit.html', {'form': form,'uuid':uuid})

def trouble_kill_list(request):
    current_user_id = request.session['user_info']['uid']
    result = models.Trouble.objects.filter(Q(reportUser_id=current_user_id)|Q(status=1)).order_by('status')
    return render(request,'Backend/backend_trouble_kill_list.html',{'result':result})

def trouble_kill(request,uuid):
    current_user_id = request.session['user_info']['uid']
    troubleResolveType = models.TroubleResolveType.objects.filter(createUser_id=current_user_id, status=1)
    if request.method == 'GET':
        ret = models.Trouble.objects.filter(uuid=uuid, processUser_id=current_user_id).count()
        # 以前未抢到
        if not ret:
            v = models.Trouble.objects.filter(uuid=uuid, status=1).update(processUser_id=current_user_id, status=2)
            if not v:
                return HttpResponse('手速太慢...')
        obj = models.Trouble.objects.filter(uuid=uuid).first()
        form = TroubleKill(initial={ 'solution': obj.processSolution})
        return render(request, 'Backend/backend_trouble_kill.html', {'obj': obj, 'form': form, 'uuid': uuid,'troubleResolveType':troubleResolveType})
    else:
        ret = models.Trouble.objects.filter(uuid=uuid, processUser_id=current_user_id, status=2).count()
        if not ret:
            return HttpResponse('订单已处理,无法修改')
        form = TroubleKill(request.POST)
        if form.is_valid():
            dic = {}
            dic['status'] = 3
            dic['processSolution'] = form.cleaned_data['solution']
            dic['processTime'] = datetime.datetime.now()
            models.Trouble.objects.filter(uuid=uuid, processUser_id=current_user_id, status=2).update(**dic)
            return redirect('/backend/trouble-kill-list.html')
        obj = models.Trouble.objects.filter(uuid=uuid).first()
        return render(request, 'backend_trouble_kill.html', {'obj': obj, 'form': form, 'uuid': uuid})

def getResolveDetail(request):
    current_user_id = request.session['user_info']['uid']
    nid =request.GET.get("nid")
    troubleResolveType = models.TroubleResolveType.objects.filter(createUser_id=current_user_id, status=1,nid=nid).first()
    ret = {'status': True, 'data': troubleResolveType.detail}
    return HttpResponse(json.dumps(ret)) 
后台逻辑

6.4 列表页面(展示自己已处理过的报障单,或者未处理的保障单)

{% extends 'Backend/backend_layout.html' %}

{% block conent %}
    <ol class="breadcrumb" style="margin-bottom: 0;">
        <li><a href="#">保障管理</a></li>
        <li class="active">处理保障列表</li>
    </ol>
    <div>
        <table class="table table-bordered">
            <thead>
            <tr>
                <th>保障标题</th>
                <th>状态</th>
                <th>创建时间</th>
                <th>创建人</th>
                <th>操作</th>
            </tr>
            </thead>
            <tbody>
            {% for row in result %}
                <tr>
                    <td>{{ row.title }}</td>
                    <td>{{ row.get_status_display }}</td>
                    <td>{{ row.createTime }}</td>
                    <td>{{ row.reportUser.username }}</td>
                    <td>
                        <a class="btn btn-primary btn-xs" href="/backend/trouble-kill-{{ row.uuid }}.html">
                            <i class="fa fa-pencil-square-o" aria-hidden="true"></i>
                            {% if row.status == 1 %}
                                抢单
                            {% elif row.status == 2 %}
                                处理订单
                            {% else %}
                                解决方案
                            {% endif %}
                        </a>
{#                        |#}
{#                        <a class="btn btn-danger btn-xs">#}
{#                            <i class="fa fa-times" aria-hidden="true"></i>#}
{#                            删除#}
{#                        </a>#}
{#                        |#}
{#                        <a class="btn btn-primary btn-xs" href="#">#}
{#                            <i class="fa fa-pencil-square-o" aria-hidden="true"></i>#}
{#                            编辑#}
{#                        </a>#}
                    </td>
                </tr>
            {% endfor %}

            </tbody>
        </table>
        <div class="clearfix">
            <ul class="pagination right" style="margin-top: 0">
               {{ page_str }}
            </ul>
        </div>
    </div>


{% endblock %}

{% block js %}

{% endblock %}
backend_trouble_kill_list.html

6.5 抢单

6.6 处理报障单(这里需要完善一个处理模板的类--TroubleResolveType) 

{% extends 'Backend/backend_layout.html' %}

{% block css %}
    <link rel="stylesheet" href="/static/plugins/kindeditor/themes/default/default.css"/>
    <style>
        .kind-content {
            width: 100%;
            min-height: 500px;
        }
    </style>
{% endblock %}

{% block conent %}
    <ol class="breadcrumb" style="margin-bottom: 0;">
        <li><a href="#">保障管理</a></li>
        <li class="active">创建报障单</li>
    </ol>
    <h1>标题</h1>
    <h3>{{ obj.title }}</h3>
    <div style="padding: 5px 8px;">
        <form method="POST" action="/backend/trouble-kill-{{ obj.uuid }}.html" novalidate>
            {% csrf_token %}
            <select id="trtSelect">
                {% for row in troubleResolveType %}
                     <option value="{{ row.nid }}">{{ row.title }}</option>
                {% endfor %}
            </select>
            <input type="checkbox" id="isTroubleResolveType" />
            <div class="form-group">
                <label for="detail">解决方案 <span>{{ form.solution.errors.0 }}</span></label>
                {{ form.solution }}
            </div>

            <div class="form-group">
                <input type="submit" class="btn btn-primary"  value="保 存">
            </div>
        </form>
    </div>


{% endblock %}

{% block js %}
    <script charset="utf-8" src="/static/plugins/kindeditor/kindeditor-all-min.js"></script>
    <script charset="utf-8" src="/static/plugins/kindeditor/lang/zh-CN.js"></script>
    <script>
        var editor = null;
        KindEditor.ready(function (K) {
            editor = K.create('#solution', {
                resizeType: 1
            });
        });
        $("#trtSelect").change(function(){
            if($("#isTroubleResolveType").is(":checked")){
                //通过ajax请求获取数据
                var typeID= $("#trtSelect").val();
                $.ajax({
                    url:'ajaxGetResolveDetail.html',
                    type:'get',
                    data:{"nid":typeID},
                    dataType:"json",
                    success:function (arg) {
                        editor.html(arg.data);
                    },
                    error:function () {
                       alert("失败了")
                    }
                    }
                )
            }
        })
    </script>
{% endblock %}
backend_trouble_kill.html

 7:分析报表

下面我们基于HighCharts做一个“工程师每月处理报障数量的分析报表”

在前台页面引入相应的js

{% extends 'Backend/backend_layout.html' %}

{% block css %}

{% endblock %}
{% block conent %}
    <ol class="breadcrumb" style="margin-bottom: 0;">
        <li class="active">报表分析</li>
    </ol>
    <div id="container" style="width: 550px; height: 400px; margin: 0 auto"></div>


{% endblock %}
{% block js %}
    <script charset="utf-8" src="/static/js/jquery-3.3.1.min.js"></script>
    <script charset="utf-8" src="/static/plugins/highcharts/highcharts.js"></script>
    <script>

        $(function () {

            initChart();

        })

        function initChart() {
            var config = {
                title: {
                    text: '月处理报障数量'
                },
                subtitle: {
                    text: 'Source: runoob.com'
                },
                xAxis: {
                    categories: ['一月', '二月', '三月', '四月', '五月', '六月'
                        , '七月', '八月', '九月', '十月', '十一月', '十二月']
                },
                yAxis: {
                    title: {
                        text: 'Temperature (\xB0C)'
                    },
                    plotLines: [{
                        value: 0,
                        width: 1,
                        color: '#808080'
                    }]
                },

                tooltip: {
                    valueSuffix: '\xB0C'
                },

                legend: {
                    layout: 'vertical',
                    align: 'right',
                    verticalAlign: 'middle',
                    borderWidth: 0
                },

                series: [
                    {
                        name: 'London',
                        data: [3.9, 4.2, 5.7, 8.5, 11.9, 15.2, 17.0,
                            16.6, 14.2, 10.3, 6.6, 4.8]
                    }
                ]
            };
            // 数据库中获取 series
            $.ajax({
                url: 'getTroubleProcessInfo.html',
                type: "get",
                dataType: "json",
                success: function (arg) {
                    debugger
                    config['series'] = arg.data;
                    config["xAxis"].categories=arg.xAxis;
                    $('#container').highcharts(config);
                }
            })
        }


    </script>
{% endblock %}
backend_trouble-statement.html
 # 报表分析
    url(r'^trouble-statement.html$', trouble.trouble_statement),
    url(r'^getTroubleProcessInfo.html$', trouble.getTroubleProcessInfo),
url
from django.shortcuts import render,redirect,HttpResponse
from repository import models
from forms.trouble import TroubleForm,TroubleKill  #引用form中的文章表单,用于添加、修改文章
from django.db.models import Q
from django.db import connection, connections
import json
import datetime #引入时间模块
def trouble_list(request):
    # user_info = request.session.get('user_info') # {id:'',}
    current_user_id = request.session['user_info']['uid']
    result = models.Trouble.objects.filter(reportUser_id=current_user_id).order_by('status').\
        only('uuid','title','status','createTime','processUser')
    return render(request,'Backend/backend_trouble_list.html',{'result': result})

def trouble_create(request):
    if request.method == 'GET':
        form = TroubleForm()
    else:
        form = TroubleForm(request.POST)
        if form.is_valid():
            dic = {}
            dic['reportUser_id'] = request.session['user_info']['uid'] # session中获取
            dic['createTime'] = datetime.datetime.now()
            dic['status'] = 1
            dic.update(form.cleaned_data)
            models.Trouble.objects.create(**dic)
            return redirect('/backend/trouble-list.html')
    return render(request, 'Backend/backend_trouble_create.html',{'form':form})

def trouble_edit(request,uuid):
    if request.method == "GET":
        obj = models.Trouble.objects.filter(uuid=uuid, status=1).only('uuid', 'title', 'detail').first()
        if not obj:
            return HttpResponse('已处理中的保单章无法修改..')
        # initial 仅初始化
        form = TroubleForm(initial={'title': obj.title,'detail': obj.detail,'uuid':obj.uuid})
        # 执行error会进行验证
        return render(request,'Backend/backend_trouble_edit.html',{'form':form,'uuid':uuid})
    else:
        form = TroubleForm(data=request.POST)
        if form.is_valid():
            # 受响应的行数
            v = models.Trouble.objects.filter(uuid=uuid, status=1).update(**form.cleaned_data)
            if not v:
                return HttpResponse('已经被处理')
            else:
                return redirect('/backend/trouble-list.html')
        return render(request, 'Backend/backend_trouble_edit.html', {'form': form,'uuid':uuid})

def trouble_kill_list(request):
    current_user_id = request.session['user_info']['uid']
    result = models.Trouble.objects.filter(Q(reportUser_id=current_user_id)|Q(status=1)).order_by('status')
    return render(request,'Backend/backend_trouble_kill_list.html',{'result':result})

def trouble_kill(request,uuid):
    current_user_id = request.session['user_info']['uid']
    troubleResolveType = models.TroubleResolveType.objects.filter(createUser_id=current_user_id, status=1)
    if request.method == 'GET':
        ret = models.Trouble.objects.filter(uuid=uuid, processUser_id=current_user_id).count()
        # 以前未抢到
        if not ret:
            v = models.Trouble.objects.filter(uuid=uuid, status=1).update(processUser_id=current_user_id, status=2)
            if not v:
                return HttpResponse('手速太慢...')
        obj = models.Trouble.objects.filter(uuid=uuid).first()
        form = TroubleKill(initial={ 'solution': obj.processSolution})
        return render(request, 'Backend/backend_trouble_kill.html', {'obj': obj, 'form': form, 'uuid': uuid,'troubleResolveType':troubleResolveType})
    else:
        ret = models.Trouble.objects.filter(uuid=uuid, processUser_id=current_user_id, status=2).count()
        if not ret:
            return HttpResponse('订单已处理,无法修改')
        form = TroubleKill(request.POST)
        if form.is_valid():
            dic = {}
            dic['status'] = 3
            dic['processSolution'] = form.cleaned_data['solution']
            dic['processTime'] = datetime.datetime.now()
            models.Trouble.objects.filter(uuid=uuid, processUser_id=current_user_id, status=2).update(**dic)
            return redirect('/backend/trouble-kill-list.html')
        obj = models.Trouble.objects.filter(uuid=uuid).first()
        return render(request, 'backend_trouble_kill.html', {'obj': obj, 'form': form, 'uuid': uuid})

def getResolveDetail(request):
    current_user_id = request.session['user_info']['uid']
    nid =request.GET.get("nid")
    troubleResolveType = models.TroubleResolveType.objects.filter(createUser_id=current_user_id, status=1,nid=nid).first()
    ret = {'status': True, 'data': troubleResolveType.detail}
    return HttpResponse(json.dumps(ret))

def trouble_statement(request):
    return render(request, 'Backend/backend_trouble-statement.html')

def getTroubleProcessInfo(request):
    cursor = connection.cursor()
    cursor.execute('select strftime("%Y-%m",processTime) as ptime from repository_trouble where status=3 group by strftime("%Y-%m",processTime)')
    xAxis = cursor.fetchall() #获取x轴上的数据
    response = []
    user_list = models.UserInfo.objects.filter()
    cursor2 = connection.cursor()
    cursor2.execute(
        """select strftime("%Y-%m",processTime) as processTime,processUser_id,count(strftime("%Y-%m",processTime)) as count from repository_trouble
where status=3
group by processUser_id,strftime("%Y-%m",processTime)"""
    )
    result = cursor2.fetchall() #获取统计数据
    print(result)
    u_id = 0;
    for user in user_list:
        curTup=[];
        for tup in result:
            if tup[1]==user.uid:
                curTup.append(tup)
            else:
                if user.uid <tup[1]:
                    break
        if curTup:
            dat=[]
            for x in xAxis:
                if curTup and x[0] == curTup[0][0]:
                    dat.append(curTup[0][2])
                    del curTup[0]
                else:
                    dat.append(0)

            temp = {
                'name': user.username,
                'data':dat
            }
            response.append(temp)
    ret = {'xAxis': xAxis, 'data': response}
    return HttpResponse(json.dumps(ret))
后台处理方法

其逻辑大致是:

利用HighCharts的页面渲染图表,通过ajax调用后台数据

 

posted @ 2019-05-26 21:02  逍遥小天狼  阅读(207)  评论(0编辑  收藏  举报