子钦加油

扩大
缩小

Django实现标签联动以及xadmin中实现标签联动

 

 

如图,即实现点击一个城市,出现对应的学校名称。开始一直以为是建立数据表的时候实现的,原来是通过ajax实现的。

思路:当get请求显示原始状态(即下拉框呈现全部内容)。当点击一个城市后,通过ajax的post方式提交,然后后端返回筛选的数据到前端,然后js先将所有的学校标签删除,创建后端传过来的学校标签

views.py

class IndexView(View):
    def get(self,request):
        citys = City.objects.all()
        schools = School.objects.all()
        return render(request,'index.html',{
            'citys':citys,
            'schools':schools,
        })
 
    def post(self,request):
        selectCity = request.POST.get('selectVal')
        schools = City.objects.get(name=selectCity).school_set.all()
        schoolLists = [ obj.name for obj in schools]
        schoolDict = dict(zip(schoolLists,schoolLists))
        print(schoolLists)
        return HttpResponse(json.dumps(schoolDict))

 前端

    $("#city ul li").on('click',function () {
 
        var selectVal = $(this).text();
        $("#city button:first").text(selectVal);
        $.ajax({
            type:'POST',
            url:"{% url 'index' %}",
            data:{'selectVal':selectVal},
            success:function(data) {
 
                var len = $("#school li a").length;
                for(var i=0;i<len;i++){
                    $("#school li a").eq(0).remove();
                }
                ret = JSON.parse(data);
                for (var obj in ret) {
                    $("#school ul").append("<li><a>"+ obj +"</a></li>");
                }
            }
        })
    });

 前端的html文件直接是bootstrap的,大致是

<div id="school" class="dropdown" style="float:left;margin-left:100px">
  <button id="i1" class="btn btn-default dropdown-toggle" type="button" id="dropdownMenu1" data-toggle="dropdown" aria-haspopup="true" aria-expanded="true">
    学校
    <span class="caret"></span>
  </button>
  <ul class="dropdown-menu" aria-labelledby="dropdownMenu1">
      {% for obj in schools %}
          <li><a href="#" data-value="{{ obj.name }}">{{ obj.name }}</a></li>
      {% endfor %}
  </ul>
</div>
 
</div>

这样,就能选择了。

 

 

2.下面是在xadmin中实现标签联动,全部按照https://blog.csdn.net/qq_16102629/article/details/81179250 做的

 

难点就是如何在注册的model中引入自定义的js文件。

models.py

class Student(models.Model):
    name = models.CharField(max_length=10,verbose_name=u'姓名',null=True,blank=True)
    school = models.ForeignKey(School,verbose_name=u'学生所在学校',null=True,blank=True)
    city = models.ForeignKey(City,verbose_name=u'学生所在城市',null=True,blank=True)
 
    class Meta:
        verbose_name = u'学生'
        verbose_name_plural = verbose_name
 
    def __str__(self):
        return self.name

自定义的xadmin.js(名字随便取)文件,放入extra_app/xadmin/static/xadmin/js 中,然后在extra_app/xadmin/widgets.py中添加自定义的xadmin.js文件中。js的id_city和id_school从页面中找到  

 

 

 

 

$('#id_city').change(function () {
        var module = $('#id_city').find('option:selected').val(); //获取父级选中值
        $('#id_school')[0].selectize.clearOptions();// 清空子级
        $.ajax({
            type: 'get',
            url: '/select/city_school/?module=' + module,
            data: '',
            async: true,
            beforeSend: function (xhr, settings) {
                xhr.setRequestHeader('X-CSRFToken', '{{ csrf_token }}')
            },
            success: function (data) {
                data = JSON.parse(data.schools)//将JSON转换
                console.log(data);
                for (var i = 0; i < data.length; i++) {
 
                    var test = {text: data[i].fields.name, value: data[i].pk, $order: i + 1}; //遍历数据,拼凑出selectize需要的格式
                    console.log(test);
                    $('#id_school')[0].selectize.addOption(test); //添加数据
                }
            },
            error: function (xhr, textStatus) {
                console.log('error')
            }
        })
    })

 接下来,视图函数

urlpatterns = [
    url(r'select/city_school/',SelectView.as_view(),name='city_school'),
]

 

from django.core import serializers
class SelectView(View):
    def get(self,request):
        print("asd")
        city_id =  request.GET.get('module','')
        schools = serializers.serialize("json", School.objects.filter(school_city_id=int(city_id)))
        print(schools)
        # 判断是否存在,输出
        if schools:
            return JsonResponse({'schools': schools})

  

 

 https://blog.csdn.net/qq_34964399/article/details/80998502

posted on 2019-12-17 20:43  子钦加油  阅读(732)  评论(0编辑  收藏  举报

导航

返回顶部