Django實現標籤聯動以及xadmin中實現標籤聯動

 

 

如圖,即實現點擊一個城市,出現對應的學校名稱。開始一直覺得是創建數據表的時候實現的,原來是經過ajax實現的。html

思路:當get請求顯示原始狀態(即下拉框呈現所有內容)。當點擊一個城市後,經過ajax的post方式提交,而後後端返回篩選的數據到前端,而後js先將全部的學校標籤刪除,建立後端傳過來的學校標籤前端

views.pyajax

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))

 前端django

    $("#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的,大體是json

<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>

這樣,就能選擇了。bootstrap

 

 

2.下面是在xadmin中實現標籤聯動,所有按照https://blog.csdn.net/qq_16102629/article/details/81179250 作的

 

難點就是如何在註冊的model中引入自定義的js文件。後端

models.pyapp

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從頁面中找到  async

 

 

 

 

$('#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

相關文章
相關標籤/搜索