1.創(chuàng)建項目和應(yīng)用后,首先在settings.py文件中配置mysql數(shù)據(jù)庫,并創(chuàng)建數(shù)據(jù)庫[省市區(qū)的sql文件,網(wǎng)上很多]
2.創(chuàng)建models模型,進行數(shù)據(jù)遷移
3.創(chuàng)建template模板文件area1.html
4.進行urls路由配置
5.編輯views視圖函數(shù)
1.models.py
?class AreaInfo(models.Model):
atitle = models.CharField(max_length=30)
aParent = models.ForeignKey('self', null=True,blank=True)?
2.urls.py
from django.conf.urlsimport url
from . import views
urlpatterns=[
? ? url(r'^area1/$', views.area1),
? ? url(r'^province/$', views.province),
? ? url(r'^city_(\d+)/$', views.city),
? ? url(r'^county_(\d+)/$', views.county),
]
3views.py
from django.shortcutsimport render
from .modelsimport AreaInfo
from django.httpimport HttpResponse, JsonResponse
def area1(request):
return render(request, 'booktest/area1.html')
#獲取省數(shù)據(jù)
def province(request):
provinceList = AreaInfo.objects.filter(aParent__isnull=True)
list1 = []
for itemin provinceList:
list1.append([item.id, item.atitle])
return JsonResponse({'data': list1})
#?獲取市數(shù)據(jù)
def city(request, pid):
print(pid)
cityList = AreaInfo.objects.filter(aParent_id=pid)
list1 = []
for itemin cityList:
list1.append([item.id, item.atitle])
return JsonResponse({'data': list1})
# 獲取縣數(shù)據(jù)
def county(request, pid):
print(pid)
countyList = AreaInfo.objects.filter(aParent_id=pid)
list1 = []for itemin countyList:
list1.append([item.id, item.atitle])
return JsonResponse({'data': list1})
4.創(chuàng)建html頁面? area.html
<html>
<head>
<title>省市區(qū)列表</title>
<script type="text/javascript" src="/static/js/jquery-1.12.4.min.js"></script>
<script>
$(function () { //獲取所有省份
$.get('/province/', function (dic) { pro = $('#pro') $.each(dic.data, function (index, item) { pro.append('' + item[1] + ''); }) })
//獲取市信息
$('#pro').change(function () {
$.get('/city_' + $(this).val() + '/', function (dict) { city = $('#city');
city.empty().append('請選擇市');
$('#county').empty().append('請選擇區(qū)縣');
$.each(dict.data, function (index, item) { city.append('' + item[1] + '');
})
});
});
//獲取區(qū)縣信息
$('#city').change(function () {
$.get('/county_' + $(this).val() + '/', function (dict) {
county = $('#county');
county.empty().append('請選擇區(qū)縣');
$.each(dict.data, function (index, item) {
county.append('' + item[1] + '');
})
})
});
})
</script>
</head>
<body>
<select id="pro">
? ? <option value="">前選擇省</option>
</select>
<select id="city">
? ? <option value="">請選擇市</option>
<select id="county">
<option value="">請選擇區(qū)縣</option>
</select>
</body>
</html>
settiong.py配置mysql數(shù)據(jù)庫
?DATABASES = {
'default': { 'ENGINE': 'django.db.backends.mysql',
'NAME': "area", 'HOST': "127.0.0.1",
'PORT': 3306, 'USER': "root",
'PASSWORD': '123456',
} }