小陆同学

python 中文名:蟒蛇,设计者:Guido van Rossum

导航

bootstrap--如何做一个doublebox双向选择器

------------恢复内容开始------------

1、首先什么是双向选择器,上图

 

 

 

类似这样的一个可以穿梭相互选择的选择器,实现方法:html+jquery+django

django-models.py

# 用户组使用了Django自带的group表
from django.contrib.auth.models import User,Group

# Group VS View_Cate 多对多关系
class View_Cate(models.Model):
    name = models.CharField(unique=True,default=None,max_length=50,verbose_name='视图名称')
    user_group = models.ManyToManyField(Group,blank=True,null=True)

    class Meta:
        db_table = 'opsmanage_view_cate'
        verbose_name_plural = '视图表'
        default_permissions = ()

html

<div class="x_content">
<table class="table" id="appListTable">
  <thead>
    <tr>
      <th>ID</th>
      <th>视图名称</th>
      <th class="text-center">操作</th>
    </tr>
  </thead>
  <tbody>
  </tbody>
</table>

</div>

jquery

var language =  {
        "sProcessing" : "处理中...",
        "sLengthMenu" : "显示 _MENU_ 项结果",
        "sZeroRecords" : "没有匹配结果",
        "sInfo" : "显示第 _START_ 至 _END_ 项结果,共 _TOTAL_ 项",
        "sInfoEmpty" : "显示第 0 至 0 项结果,共 0 项",
        "sInfoFiltered" : "(由 _MAX_ 项结果过滤)",
        "sInfoPostFix" : "",
        "sSearch" : "搜索: ",
        "sUrl" : "",
        "sEmptyTable" : "表中数据为空",
        "sLoadingRecords" : "载入中...",
        "sInfoThousands" : ",",
        "oPaginate" : {
            "sFirst" : "首页",
            "sPrevious" : "上页",
            "sNext" : "下页",
            "sLast" : "末页"
        },
        "oAria" : {
            "sSortAscending" : ": 以升序排列此列",
            "sSortDescending" : ": 以降序排列此列"
        }
    }
function InitDataTable(tableId,url,buttons,columns,columnDefs){
      var data = requests('get',url)
      oOverviewTable =$('#'+tableId).dataTable(
              {
                    "dom": "Bfrtip",
                    "buttons":buttons,
                    "bScrollCollapse": false,
                    "bRetrieve": true,
                    "destroy": true,
                    "data":    data,
                    "columns": columns,
                    "columnDefs" :columnDefs,
                    "language" : language,
                    "order": [[ 0, "ase" ]],
                    "autoWidth": false
                });
    }
$(document).ready(function()
{
    makeAppsManageTableList()
})
function makeAppsManageTableList(){
    var columns = [
                   {"data": "id"},
                   {"data": "name"}
                   ]
   var columnDefs = [
                        {
                           targets: [2],
                           render: function(data, type, row, meta) {
                               return '<div class="btn-view  btn-view-xs">' +
                                       '<button type="button" name="btn-view-edit" value="'+ row.id +'" class="btn btn-default"><span class="fa fa-edit" aria-hidden="true"></span>' +
                                       '</button>' +
                                       '<button type="button" name="btn-view-group" value="'+ row.id +'" class="btn btn-default" data-toggle="modal" data-target=".bs-example-modal-group-group">分配组' +
                                        '</button>' +
                                       '<button type="button" name="btn-view-delete" value="'+ row.id +'" class="btn btn-default" aria-label="Justify"><span class="glyphicon glyphicon-trash" aria-hidden="true"></span>' +
                                       '</button>' +
                                       '</div>';
                           },
                           "className": "text-center",
                        },
                      ]
    var buttons = [{
        text: '<span class="fa fa-plus"></span>',
        className: "btn-xs",
        action: function ( e, dt, node, config ) {
            addViews()
        }
    }]
    InitDataTable('appListTable','/api/queryView/',buttons,columns,columnDefs);
}

 

 

 

 

 

jquery

$("#viewGroupSubmit").on('click', function() {
   var vIds = $(this).val();
   var vServer = $('[name="user-group-doublebox"]').val()
   if (vServer){
      $.ajax({
         type: "POST",
         url:"/api/cate/info/"+vIds+'/',
         data:{
            "type":"modf_view_group",
            "id": vIds,
            "groups":vServer
         },
         error: function(response) {
            new PNotify({
               title: 'Ops Failed!',
               text: response.responseText,
               type: 'error',
               styling: 'bootstrap3'
            });
         },
         success: function(response) {
            if (response["code"] == 200){
               new PNotify({
                  title: 'Success!',
                  text: '修改成功',
                  type: 'success',
                  styling: 'bootstrap3'
               });
            }else{
               new PNotify({
                  title: 'Ops Failed!',
                  text: response["msg"],
                  type: 'error',
                  styling: 'bootstrap3'
               });
            }
         }
      });
   }else{
      $.confirm({
         title: '<strong>警告</strong>',
         typeAnimated: true,
         content: "没有选择任何用户组~",
         type: 'red'
      });
   }

});

 html

        <div  class="modal fade bs-example-modal-group-group" data-backdrop="static"  tabindex="-1" role="dialog" aria-hidden="true">
          <div class="modal-dialog modal-lg">
            <div class="modal-content">

              <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">×</span>
                </button>
                <h4 class="modal-title" id="myUserGroupsModalLabel">分组管理</h4>
              </div>
              <div class="modal-body ue-container">

                 <select multiple="multiple" size="10" name="user-group-doublebox" class="demo">
                    </select>

              </div>
              <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                <button type="button" id="viewGroupSubmit"  class="btn btn-primary">保存</button>
              </div>

            </div>
          </div>
        </div>

jquery

function GetViewOrGroups(url,uid){
    var aList = []
    var sList = []
    var url = url + uid +'/?type=get_user_group'
    response = requests('get',url)
    if(response["code"]=="200"){
        for (var i=0; i <response["data"].length; i++){
            if (response["data"][i]["apps_name"]){
                var name = response["data"][i]["apps_name"]+ ' - ' + response["data"][i]["name"]
            }else{
                var name = response["data"][i]["name"]
            }
            if(response["data"][i]["status"]==1){
                sList.push({"id":response["data"][i]["id"],"name":name})
            }
            else{
                aList.push({"id":response["data"][i]["id"],"name":name})
            }
        }

    }
    return {"group":sList,"all":aList}
}

django-views.py

        if request.GET.get('type') == 'get_user_group':
            # todo 视图与角色组关联关系
            cates = App_Cate.objects.filter(id=id).first()
            selected_group = [group for group in cates.user_group.all()]
            groupList = []
            for group in Group.objects.all():
                groupDict = {}
                groupDict['id'] = group.id
                groupDict['name'] = group.name
                if group in selected_group:
                    groupDict['status'] = 1

                else:
                    groupDict['status'] = 0
                groupList.append(groupDict)
            return JsonResponse({'code':200,'data':groupList})

以上即可拿到数据渲染双向选择器,效果如图一

jquery

$("#viewGroupSubmit").on('click', function() {
    var vIds = $(this).val();
    var vServer = $('[name="user-group-doublebox"]').val()
    if (vServer){
        $.ajax({
            type: "POST",
            url:"/api/cate/info/"+vIds+'/',
            data:{
                "type":"modf_view_group",
                "id": vIds,
                "groups":vServer
            },
            error: function(response) {
                new PNotify({
                    title: 'Ops Failed!',
                    text: response.responseText,
                    type: 'error',
                    styling: 'bootstrap3'
                });
            },
            success: function(response) {
                if (response["code"] == 200){
                    new PNotify({
                        title: 'Success!',
                        text: '修改成功',
                        type: 'success',
                        styling: 'bootstrap3'
                    });
                }else{
                    new PNotify({
                        title: 'Ops Failed!',
                        text: response["msg"],
                        type: 'error',
                        styling: 'bootstrap3'
                    });
                }
            }
        });
    }else{
        $.confirm({
            title: '<strong>警告</strong>',
            typeAnimated: true,
            content: "没有选择任何用户组~",
            type: 'red'
        });
    }

});

django-views.py

        if data.get('type') == 'modf_view_group':
            cate = View_Cate.objects.filter(id=id).first()
            groupList = [int(i) for i in request.POST.getlist('groups[]')]
            addGroupsList = list(set(groupList).difference(set(cate.user_group.all())))
            delGroupsList = list(set(cate.user_group.all()).difference(set(groupList)))
            for groupObj in delGroupsList:
                cate.user_group.remove(groupObj)
            for groupId in addGroupsList:
                appObj = Group.objects.filter(id=groupId).first()
                cate.user_group.add(grouppObj)
            return JsonResponse({'code': 200, 'msg': '修改成功'})

大功告成

------------恢复内容结束------------

posted on 2020-02-28 21:41  小陆同学  阅读(1555)  评论(0编辑  收藏  举报