code management

This commit is contained in:
RobbieHan
2018-12-19 21:41:50 +08:00
parent 00f7112b67
commit 860ae14d4c
10 changed files with 687 additions and 6 deletions

46
apps/cmdb/forms.py Normal file
View File

@@ -0,0 +1,46 @@
# @Time : 2018/12/19 16:13
# @Author : RobbieHan
# @File : forms.py
from django import forms
from .models import Code
class CodeCreateForm(forms.ModelForm):
class Meta:
model = Code
fields = '__all__'
error_messages = {
'key': {'required': 'key不能为空'},
'value': {'required': 'value不能为空'}
}
def clean(self):
cleaned_data = super(CodeCreateForm, self).clean()
key = cleaned_data.get('key')
value = cleaned_data.get('value')
if Code.objects.filter(key=key).count():
raise forms.ValidationError('key{}已存在'.format(key))
if Code.objects.filter(value=value).count():
raise forms.ValidationError('value: {}已存在'.format(value))
class CodeUpdateForm(CodeCreateForm):
def clean(self):
cleaned_data = self.cleaned_data
key = cleaned_data.get('key')
value = cleaned_data.get('value')
if self.instance:
matching_code = Code.objects.exclude(pk=self.instance.pk)
if matching_code.filter(key=key).exists():
msg = 'key{} 已经存在'.format(key)
raise forms.ValidationError(msg)
if matching_code.filter(value=value).exists():
msg = 'value{} 已经存在'.format(value)
raise forms.ValidationError(msg)

View File

@@ -1,9 +1,15 @@
from django.urls import path
from .views import CmdbView
from . import views_code
app_name = 'cmdb'
urlpatterns = [
path('', CmdbView.as_view(), name='index'),
path('portal/code/', views_code.CodeView.as_view(), name='portal-code'),
path('portal/code/create/', views_code.CodeCreateView.as_view(), name='portal-code-create'),
path('portal/code/list/', views_code.CodeListView.as_view(), name='portal-code-list'),
path('portal/code/update/', views_code.CodeUpdateView.as_view(), name='portal-code-update'),
path('portal/code/delete/', views_code.CodeDeleteView.as_view(), name='portal-code-delete'),
]

53
apps/cmdb/views_code.py Normal file
View File

@@ -0,0 +1,53 @@
# @Time : 2018/12/19 13:31
# @Author : RobbieHan
# @File : views_code.py.py
from django.views.generic import TemplateView
from system.mixin import LoginRequiredMixin
from custom import (BreadcrumbMixin, SandboxCreateView,
SandboxListView, SandboxUpdateView, SandboxDeleteView)
from .models import Code
from .forms import CodeCreateForm, CodeUpdateForm
class CodeView(LoginRequiredMixin, BreadcrumbMixin, TemplateView):
template_name = 'cmdb/code.html'
def get_context_data(self):
context = dict(code_parent=Code.objects.filter(parent=None))
return context
class CodeCreateView(SandboxCreateView):
model = Code
form_class = CodeCreateForm
template_name_suffix = '_create'
def get_context_data(self, **kwargs):
kwargs['code_parent'] = Code.objects.filter(parent=None)
return super().get_context_data(**kwargs)
class CodeListView(SandboxListView):
model = Code
fields = ['id', 'key', 'value', 'parent__value']
def get(self, request):
if 'parent' in request.GET and request.GET['parent']:
self.filters = dict(parent__key=request.GET['parent'])
return super().get(request)
class CodeUpdateView(SandboxUpdateView):
model = Code
form_class = CodeUpdateForm
template_name_suffix = '_update'
def get_context_data(self, **kwargs):
kwargs['code_parent'] = Code.objects.filter(parent=None)
return super().get_context_data(**kwargs)
class CodeDeleteView(SandboxDeleteView):
model = Code

View File

@@ -3,10 +3,13 @@
# @File : custom.py
import json
import re
from django.views.generic import CreateView, UpdateView
from django.views.generic import CreateView, UpdateView, View
from django.shortcuts import HttpResponse
from django.http import Http404
from django.http import Http404, JsonResponse
from django.db.models.query import QuerySet
from django.core.exceptions import ImproperlyConfigured
from system.mixin import LoginRequiredMixin
from system.models import Menu
@@ -42,6 +45,69 @@ class SandboxGetObjectMixin:
return obj
class SandboxMultipleObjectMixin:
filters = {}
fields = []
queryset = None
model = None
def get_queryset(self):
if self.queryset is not None:
queryset = self.queryset
if isinstance(queryset, QuerySet):
queryset = queryset.all()
elif self.model is not None:
queryset = self.model._default_manager.all()
else:
raise ImproperlyConfigured(
"%(cls)s is missing a QuerySet. Define "
"%(cls)s.model, %(cls)s.queryset."
% {'cls': self.__class__.__name__}
)
return queryset
def get_datatables_paginator(self, request):
datatables = request.GET
draw = int(datatables.get('draw'))
start = int(datatables.get('start'))
length = int(datatables.get('length'))
order_column = datatables.get('order[0][column]')
order_dir = datatables.get('order[0][dir]')
order_field = datatables.get('columns[{}][data]'.format(order_column))
queryset = self.get_queryset()
if order_dir == 'asc':
queryset = queryset.order_by(order_field)
else:
queryset = queryset.order_by('-{0}'.format(order_field))
record_total_count = queryset.count()
filters = self.get_filters()
fields = self.get_fields()
if filters:
queryset = queryset.filter(**self.filters)
if fields:
queryset = queryset.values(*self.fields)
record_filter_count = queryset.count()
object_list = queryset[start:(start + length)]
data = list(object_list)
return {
'draw': draw,
'recordsTotal': record_total_count,
'recordsFiltered': record_filter_count,
'data': data,
}
def get_filters(self):
return self.filters
def get_fields(self):
return self.fields
class SandboxEditViewMixin:
def post(self, request, *args, **kwargs):
@@ -50,6 +116,11 @@ class SandboxEditViewMixin:
if form.is_valid():
form.save()
res['result'] = True
else:
pattern = '<li>.*?<ul class=.*?><li>(.*?)</li>'
form_errors = str(form.errors)
errors = re.findall(pattern, form_errors)
res['error'] = errors[0]
return HttpResponse(json.dumps(res), content_type='application/json')
@@ -65,3 +136,27 @@ class SandboxUpdateView(LoginRequiredMixin, SandboxEditViewMixin, SandboxGetObje
def post(self, request, *args, **kwargs):
self.object = self.get_object()
return super().post(request, *args, **kwargs)
class SandboxListView(LoginRequiredMixin, SandboxMultipleObjectMixin, View):
"""
JsonResponse some json of objects, set by `self.model` or `self.queryset`.
"""
def get(self, request):
context = self.get_datatables_paginator(request)
return JsonResponse(context)
class SandboxDeleteView(LoginRequiredMixin, SandboxMultipleObjectMixin, View):
def post(self, request):
context = dict(result=False)
queryset = self.get_queryset()
if 'id' in request.POST and request.POST['id']:
id_list = map(int, request.POST['id'].split(','))
queryset.filter(id__in=id_list).delete()
context['result'] = True
else:
raise AttributeError("Sandbox delete view %s must be called with id. "
% self.__class__.__name__)
return JsonResponse(context)

View File

@@ -1,2 +1 @@
django==2.1.2
pillow==5.3.0
-r pro.txt

View File

@@ -1,2 +1,14 @@
django==2.1.2
pillow==5.3.0
pillow==5.3.0
mysqlclient==1.3.13
ipython==7.1.1
pyyaml==3.13
ruamel.yaml==0.15.80
python-nmap==0.6.1
redis==3.0.1
pymongo==3.7.1
paramiko==2.4.2
pycrypto==2.6.1
celery==4.2.1
celery-once==2.0.0
flower==0.9.2

View File

@@ -2,7 +2,7 @@ var DATATABLES_CONSTANT = {
// datatables常量
DATA_TABLES : {
DEFAULT_OPTION : { // DataTables初始化选项
SERVER_SIDE_OPTION : { // DataTables初始化选项
oLanguage : {
sProcessing : "处理中...",
sLengthMenu : "每页 _MENU_ 项",//"显示 _MENU_ 项结果,",

274
templates/cmdb/code.html Normal file
View File

@@ -0,0 +1,274 @@
{% extends "base-left.html" %}
{% load staticfiles %}
{% block css %}
<link rel="stylesheet" href="{% static 'plugins/datatables/jquery.dataTables.min.css' %}">
<link rel="stylesheet" href="{% static 'js/plugins/layer/skin/layer.css' %}">
<link rel="stylesheet" href="{% static 'plugins/select2/select2.min.css' %}">
{% endblock %}
{% block content %}
<!-- Main content -->
<section class="content">
<div id="devlist">
<div class="box box-primary" id="liebiao">
<div class="box-header">
<div class="btn-group pull-left">
<button type="button" id="btnRefresh" class="btn btn-default">
<i class="glyphicon glyphicon-repeat"></i>刷新
</button>
</div>
<div class="btn-group pull-left">&nbsp</div>
<div class="btn-group pull-left">
<button type="button" id="btnCreate" class="btn btn-default">
<i class="glyphicon glyphicon-plus"></i>新增
</button>
</div>
<div class="btn-group pull-left">&nbsp</div>
<div class="btn-group pull-left">
<button type="button" id="btnDelete" class="btn btn-default">
<i class="glyphicon glyphicon-trash"></i>删除
</button>
</div>
<div class="pull-right">
<form class="form-inline" id="queryForm">
<div class="form-group searchArea margin-r-5 margin-top-5">
<label>字典分类</label>
<select class="form-control inputText select2" name="parent" id="parent">
<option style='text-align:center' value="">---所有---</option>
{% for code in code_parent %}
<option value={{ code.key}}>{{ code.value }}</option>
{% endfor %}
</select>
</div>
</form>
</div>
</div>
<div class="box-body">
<table id="dtbList" class="display" cellspacing="0" width="100%">
<thead>
<tr valign="middle">
<th><input type="checkbox" id="checkAll"></th>
<th>ID</th>
<th>KEY</th>
<th>VALUE</th>
<th>所属</th>
<th>操作</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
<br> <br>
</div>
</div>
</div>
</section>
<!-- /.content -->
{% endblock %}
{% block javascripts %}
<script src="{% static 'plugins/datatables/jquery.dataTables.min.js' %}"></script>
<script src="{% static 'plugins/datatables/dataTables.const-1.js' %}"></script>
<script src="{% static 'js/plugins/layer/layer.js' %}"></script>
<script src="{% static 'plugins/select2/select2.full.min.js' %}"></script>
<script type="text/javascript">
// 菜单选中高亮
$(function () {
$('#CMDB-PORTAL').addClass('active');
$('#CDMB-PORTAL-CODE').addClass('active');
});
// datatables 初始化配置
var oDataTable = null;
$(function () {
oDataTable = initTable();
function initTable() {
var oTable = $('#dtbList').DataTable($.extend(true, {},
DATATABLES_CONSTANT.DATA_TABLES.SERVER_SIDE_OPTION,
{
ajax: {
"url": "{% url 'cmdb:portal-code-list' %}",
"data": function (d) {
d.parent = $("#parent").val();
}
},
columns: [
DATATABLES_CONSTANT.DATA_TABLES.COLUMN.CHECKBOX,
{
data: "id",
width: "5%",
},
{
data: "key",
//width : "20%",
},
{
data: "value",
//width : "20%",
},
{
data: "parent__value",
//width : "20%",
},
{
data: "id",
width: "10%",
bSortable: "false",
render: function (data, type, row, meta) {
var ret = "";
var ret = "<button title='详情' onclick='doUpdate("
+ data + ")'><i class='glyphicon glyphicon-pencil'></i></button>";
ret = ret + "<button title='删除' onclick='doDelete("
+ data + ")'><i class='glyphicon glyphicon-trash'></i></button>";
return ret;
}
}],
}));
return oTable;
}
});
//select2
$(function () {
//Initialize Select2 Elements
$(".select2").select2();
});
//过滤刷新接口获取新的数据
$("#parent").change(function () {
oDataTable.ajax.reload();
});
// 刷新数据
$("#btnRefresh").click(function () {
oDataTable.ajax.reload();
});
//新建字典
$("#btnCreate").click(function () {
layer.open({
type: 2,
title: '新增',
shadeClose: false,
maxmin: true,
area: ['800px', '400px'],
content: "{% url 'cmdb:portal-code-create' %}",
end: function () {
//关闭时做的事情
oDataTable.ajax.reload();
}
});
});
//修改字典
function doUpdate(id) {
layer.open({
type: 2,
title: '编辑',
shadeClose: false,
maxmin: true,
area: ['800px', '400px'],
content: ["{% url 'cmdb:portal-code-update' %}" + '?id=' + id, 'no'],
end: function () {
oDataTable.ajax.reload();
}
});
}
//checkbox全选
$("#checkAll").on("click", function () {
if ($(this).prop("checked") === true) {
$("input[name='checkList']").prop("checked", $(this).prop("checked"));
$('#example tbody tr').addClass('selected');
} else {
$("input[name='checkList']").prop("checked", false);
$('#example tbody tr').removeClass('selected');
}
});
//批量删除
$("#btnDelete").click(function () {
if ($("input[name='checkList']:checked").length == 0) {
layer.msg("请选择要删除的记录");
return;
}
var arrId = new Array();
$("input[name='checkList']:checked").each(function () {
//alert($(this).val());
arrId.push($(this).val());
});
sId = arrId.join(',');
layer.alert('确定删除吗?', {
title: '提示'
, icon: 3 //0:感叹号 1对号 2差号 3问号 4小锁 5哭脸 6笑脸
, time: 0 //不自动关闭
, btn: ['YES', 'NO']
, yes: function (index) {
layer.close(index);
$.ajax({
type: "POST",
url: "{% url 'cmdb:portal-code-delete' %}",
data: {"id": sId, csrfmiddlewaretoken: '{{ csrf_token }}'},
cache: false,
success: function (msg) {
if (msg.result) {
layer.alert("操作成功", {icon: 1});
oDataTable.ajax.reload();
} else {
//alert(msg.message);
layer.alert("操作失败", {icon: 2});
}
return;
}
});
}
});
});
//删除单个数据
function doDelete(id) {
layer.alert('确定删除吗?', {
title: '提示'
, icon: 3 //0:感叹号 1对号 2差号 3问号 4小锁 5哭脸 6笑脸
, time: 0 //不自动关闭
, btn: ['YES', 'NO']
, yes: function (index) {
layer.close(index);
$.ajax({
type: "POST",
url: "{% url 'cmdb:portal-code-delete' %}",
data: {"id": id, csrfmiddlewaretoken: '{{ csrf_token }}'},
cache: false,
success: function (msg) {
if (msg.result) {
layer.alert('删除成功', {icon: 1});
oDataTable.ajax.reload();
} else {
//alert(msg.message);
layer.alert('删除失败', {icon: 2});
}
return;
}
});
}
});
}
</script>
{% endblock %}

View File

@@ -0,0 +1,97 @@
{% extends 'base-layer.html' %}
{% load staticfiles %}
{% block css %}
<link rel="stylesheet" href="{% static 'plugins/select2/select2.min.css' %}">
<!-- iCheck for checkboxes and radio inputs -->
{% endblock %}
{% block main %}
<div class="box box-danger">
<form class="form-horizontal" id="addForm" method="post">
{% csrf_token %}
<div class="box-body">
<fieldset>
<legend>
<h4>新建字典</h4>
</legend>
<div class="form-group has-feedback">
<label class="col-sm-2 control-label">KEY</label>
<div class="col-sm-3">
<input class="form-control" name="key" type="text"/>
</div>
<label class="col-sm-2 control-label">VALUE</label>
<div class="col-sm-3">
<input class="form-control" name="value" type="text" />
</div>
</div>
<div class="form-group has-feedback">
<label class="col-sm-2 control-label">父菜单</label>
<div class="col-sm-3">
<select class="form-control select2" name="parent">
<option value=""></option>
{% for parent in code_parent %}
<option value={{ parent.id }}> {{ parent.value }} </option>
{% endfor %}
</select>
</div>
<label class="col-sm-2 control-label">描述信息</label>
<div class="col-sm-3">
<input class="form-control" id="desc" name="desc" type="text" />
</div>
</div>
</fieldset>
</div>
<div class="box-footer ">
<div class="row span7 text-center ">
<button type="button" id="btnCancel" class="btn btn-default margin-right ">重置</button>
<button type="button" id="btnSave" class="btn btn-info margin-right ">保存</button>
</div>
</div>
</form>
</div>
{% endblock %}
{% block javascripts %}
<script src="{% static 'plugins/select2/select2.full.min.js' %}"></script>
<script type="text/javascript">
$("#btnSave").click(function () {
var data = $("#addForm").serialize();
$.ajax({
type: $("#addForm").attr('method'),
url: "{% url 'cmdb:portal-code-create' %}",
data: data,
cache: false,
success: function (msg) {
if (msg.result) {
layer.alert('数据保存成功!', {icon: 1}, function (index) {
parent.layer.closeAll(); //关闭所有弹窗
});
} else {
layer.alert(msg.error, {icon: 5});
//$('errorMessage').html(msg.message)
}
return;
}
});
});
/*点取消刷新新页面*/
$("#btnCancel").click(function () {
window.location.reload();
});
$(function () {
//Initialize Select2 Elements
$(".select2").select2();
});
</script>
{% endblock %}

View File

@@ -0,0 +1,99 @@
{% extends 'base-layer.html' %}
{% load staticfiles %}
{% block css %}
<link rel="stylesheet" href="{% static 'plugins/select2/select2.min.css' %}">
<!-- iCheck for checkboxes and radio inputs -->
{% endblock %}
{% block main %}
<div class="box box-danger">
<form class="form-horizontal" id="addForm" method="post">
<input type="hidden" name='id' type='text' value="{{ code.id }}"/>
{% csrf_token %}
<div class="box-body">
<fieldset>
<legend>
<h4>修改字典</h4>
</legend>
<div class="form-group has-feedback">
<label class="col-sm-2 control-label">KEY</label>
<div class="col-sm-3">
<input class="form-control" name="key" type="text" value="{{ code.key }}"/>
</div>
<label class="col-sm-2 control-label">VALUE</label>
<div class="col-sm-3">
<input class="form-control" name="value" type="text" value="{{ code.value }}"/>
</div>
</div>
<div class="form-group has-feedback">
<label class="col-sm-2 control-label">父菜单</label>
<div class="col-sm-3">
<select class="form-control select2" name="parent">
<option value={{ code.parent.id }}> {{ code.parent.value }} </option>
<option value=""></option>
{% for parent in code_parent %}
<option value={{ parent.id }}> {{ parent.value }} </option>
{% endfor %}
</select>
</div>
<label class="col-sm-2 control-label">描述信息</label>
<div class="col-sm-3">
<input class="form-control" id="desc" name="desc" type="text" />
</div>
</div>
</fieldset>
</div>
<div class="box-footer ">
<div class="row span7 text-center ">
<button type="button" id="btnCancel" class="btn btn-default margin-right ">重置</button>
<button type="button" id="btnSave" class="btn btn-info margin-right ">保存</button>
</div>
</div>
</form>
</div>
{% endblock %}
{% block javascripts %}
<script src="{% static 'plugins/select2/select2.full.min.js' %}"></script>
<script type="text/javascript">
$("#btnSave").click(function () {
var data = $("#addForm").serialize();
$.ajax({
type: $("#addForm").attr('method'),
url: "{% url 'cmdb:portal-code-update' %}",
data: data,
cache: false,
success: function (msg) {
if (msg.result) {
layer.alert('数据保存成功!', {icon: 1}, function (index) {
parent.layer.closeAll(); //关闭所有弹窗
});
} else {
layer.alert(msg.error, {icon: 5});
//$('errorMessage').html(msg.message)
}
return;
}
});
});
/*点取消刷新新页面*/
$("#btnCancel").click(function () {
window.location.reload();
});
$(function () {
//Initialize Select2 Elements
$(".select2").select2();
});
</script>
{% endblock %}