1. 程式人生 > >DJANGO實現下拉框的二級聯動

DJANGO實現下拉框的二級聯動

環境:PYTHON2.7+DJANGO1.9

有資料表如下,就是想在每次下拉框選擇dnsname欄位的時候,帶出對應的hostipaddr欄位

實現如下

models.py

from __future__ import unicode_literals

from django.db import models

class systeminfo(models.Model):
    id = models.IntegerField(primary_key=True)
    dnsname = models.CharField(max_length=50)
    hostipaddr = models.CharField(max_length=50)
    hostuname = models.CharField(max_length=50)
    hostupwd = models.CharField(max_length=100)
    systempath = models.CharField(max_length=100)
    systemtemppath = models.CharField(max_length=100)
    systemstartcmd = models.CharField(max_length=100)
    systemstopcmd = models.CharField(max_length=100)

urls.py   注意下面兩行即可

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^addsysteminfo/$',views.addsysteminfo,name='addsysteminfo'),
    url(r'^updatesystem/$',views.updatesystem,name='updatesystem'),
    url(r'^getipaddr/$',views.getipaddr,name='getipaddr'),
]

 

views.py實現的方法,注意這是兩個方法,一個載入第一級的下拉框,一個在第一級的下拉框發生change事件的時候返回

json格式的資料以供二級下拉框載入

from django.shortcuts import render
import django
import models
import pwden
from django.http import JsonResponse
def updatesystem(request):
    if request.method=="POST":
        pass
    else:
        try:
            dnsnamelist=models.systeminfo.objects.all().values("dnsname").distinct()
        except Exception:
            return render(request,"updatesystem.html",{"login_err":"loaddnsnamefail"})



        return render(request,"updatesystem.html",{"dnsnamelist":dnsnamelist})


def getipaddr(request):
    if request.method == 'GET':
        seldnsname=request.GET.get('seldnsname')
        if seldnsname:
            data = list(models.systeminfo.objects.filter(dnsname=seldnsname).values("hostipaddr"))
            return JsonResponse(data, safe=False)

 

updatesystem.html前端的HTML

<!DOCTYPE html>
<html lang="UTF-8">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<form enctype="multipart/form-data" action="{% url 'updatesystem' %}" method="post">
    {% csrf_token %}
   系統名稱:<select name="seldnsname" id="systemname">
    <option value ="請選擇">請選擇</option>
    {% for dnsnames in dnsnamelist %}
        <option value ={{ dnsnames.dnsname }}>{{ dnsnames.dnsname }}</option>
    {% endfor %}
</select></br>
</br>
主機名稱:<select name="selhostipaddrs" id="hostnames">

</select>
</br>
</br>

   <input type="submit" value="更新應用" />
    </br>

    </br>
    <h4 style="color: red"><b>{{ login_err }}</b></h4>

<script src="https://code.jquery.com/jquery-3.1.0.min.js"></script>
<script language="JavaScript">
    $("#systemname").change(function() {
      var dnsname = $(this).val();
{#alert("welcome");#}
      $.ajax({
        url: '/getipaddr/',

          data:{"seldnsname":$(this).val()},
     type: 'GET',
        dataType: 'json',
        success: function (data) {
            var content='';
            $.each(data, function(i, item){
                  content+='<option value='+item.hostipaddr+'>'+item.hostipaddr+'</option>'
                });
            $('#hostnames').html(content)
        },

      });
    });


</script>
</form>
</body>
</html>

展示的效果如下:

 

這個結果就和預期的效果一樣