我是一个django新手,想写一个省市的二级联动,结果在网上找了N久,要么是不全,要么是太复杂看不懂,最终实现了二级联动,分享给django web开发新手。
参考博客http://sarlmolapple.is-programmer.com/posts/25844.html文中部分代码为该博客中复制
第一步:创建project和app这里就不写了,相信只要是刚开始接触django的都能知道如何创建,我这里的ProjectName是testccc,AppName是app
第二步:创建model(app/models.py)并插入数据,插入数据就不啰嗦了
from django.db import models class Province(models.Model): provinceName = models.CharField(max_length = 20) class City(models.Model): cityName = models.CharField(max_length = 20) provinceID = models.ForeignKey(Province)
第三步:创建form(app/forms.py)
#coding=utf8 from django import forms from .models import * provinces = Province.objects.all() PROVINCE_CHOICES = [] for province in provinces: PROVINCE_CHOICES.append([province.id, province.provinceName]) class myForm(forms.Form): province = forms.ChoiceField(widget = forms.Select(attrs={'class':'select', 'onChange':'getCityOptions(this.value)'}), choices = PROVINCE_CHOICES, label= u'选择省') city = forms.ChoiceField(widget = forms.Select(attrs={'class':'select'}), label = u'选择市') #如果需要3级联动,在city中也添加onChange参数指定就jquery函数
第四步:创建模版(app/templates/test.html)
<script src="/js/jquery.js" type="text/javascript"></script> <script type="text/javascript"> function getCityOptions(province_id){ $.ajax({ type: "GET", url: "/getcitylist?provinceID="+province_id, dataType:'json', success: function(data,textStatus){ var citySelect = document.getElementById("id_city"); for ( var i=citySelect.options.length-1; i>-1; i--){ citySelect[i] = null; } if(data.length > 0) { $("#id_city").show(); for(i=0;i<data.length;i++){ citySelect.options[i] = new Option(); citySelect.options[i].text = data[i].label; citySelect.options[i].value = data[i].text; } }else $("#id_city").hide(); } }) } </script> <label>省市:</label> `form`
第五步:创建view函数(app/views.py)
from django.shortcuts import render_to_response from django.http import HttpResponse from testccc.app.models import * from testccc.app.forms import * # 1.5以前的版本 from django.utils import simplejson # 1.5以后的版本 import json def city_list(request,provinceID): city_list = [] province = request.GET['provinceID'] citys = City.objects.filter(provinceID = province) for city in citys: c = {} c['label'] = city.cityName c['text'] = city.id city_list.append(c) # 1.5以前的版本 return HttpResponse(simplejson.dumps(city_list), mimetype='application/json') # 1.5以后的版本 return HttpResponse(json.dumps(city_list), mimetype='application/json') def test(request): form = myForm() return render_to_response('test.html',locals())
第六步:创建url (usrs.py)
urlpatterns = patterns('', #由于在html模版中调用了静态jquery.js文件,所以首先需要在url中指定js静态文件的路径,这个路径也可以用来调用css和img文件 url(r'^js/(?P<path>.*)$', 'django.views.static.serve', {'document_root': '//root/workspace/testccc/testccc/static/js'}), #js函数调用的url url(r'^getcitylist/(.*)$','testccc.app.views.city_list'), url(r'^test/$','testccc.app.views.test'), )
第七步:启动并测试