您好,登錄后才能下訂單哦!
我是一個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'), )
第七步:啟動并測試
訪問 http://localhost/test
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。