1.创建项目和应用后,首先在settings.py文件中配置mysql数据库,并创建数据库[省市区的sql文件,网上很多]
2.创建models模型,进行数据迁移
3.创建template模板文件area1.html
4.进行urls路由配置
5.编辑views视图函数
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')
#获取省数据
def province(request):
provinceList = AreaInfo.objects.filter(aParent__isnull=True)
list1 = []
for itemin provinceList:
list1.append([item.id, item.atitle])
return JsonResponse({'data': list1})
# 获取市数据
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})
# 获取县数据
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.创建html页面 area.html
<html>
<head>
<title>省市区列表</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('请选择区县');
$.each(dict.data, function (index, item) { city.append('' + item[1] + '');
})
});
});
//获取区县信息
$('#city').change(function () {
$.get('/county_' + $(this).val() + '/', function (dict) {
county = $('#county');
county.empty().append('请选择区县');
$.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="">请选择区县</option>
</select>
</body>
</html>
settiong.py配置mysql数据库
DATABASES = {
'default': { 'ENGINE': 'django.db.backends.mysql',
'NAME': "area", 'HOST': "127.0.0.1",
'PORT': 3306, 'USER': "root",
'PASSWORD': '123456',
} }