环境: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
Title
展示的效果如下:
这个结果就和预期的效果一样