django实现省市县三级联动
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了django实现省市县三级联动相关的知识,希望对你有一定的参考价值。
1.创建项目和应用后,首先在settings.py文件中配置mysql数据库,并创建数据库[省市区的sql文件,网上很多]
2.创建models模型,进行数据迁移
3.创建template模板文件area1.html
4.进行urls路由配置
5.编辑views视图函数
1.modles.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.urls import 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), ]
3.views.py
from django.shortcuts import render from .models import AreaInfo from django.http import HttpResponse, JsonResponse def area1(request): return render(request, ‘booktest/area1.html‘) # 获取省数据 def province(request): provinceList = AreaInfo.objects.filter(aParent__isnull=True) list1 = [] for item in 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 item in 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 item in countyList: list1.append([item.id, item.atitle]) return JsonResponse({‘data‘: list1})
4.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(‘<option value=‘ + item[0] + ‘>‘ + item[1] + ‘</option>‘); }) }) //获取市信息 $(‘#pro‘).change(function () { $.get(‘/city_‘ + $(this).val() + ‘/‘, function (dict) { city = $(‘#city‘); city.empty().append(‘<option value="">请选择市</option>‘); $(‘#county‘).empty().append(‘<option value="">请选择区县</option>‘); $.each(dict.data, function (index, item) { city.append(‘<option value=‘ + item[0] + ‘>‘ + item[1] + ‘</option>‘); }) }); }); //获取区县信息 $(‘#city‘).change(function () { $.get(‘/county_‘ + $(this).val() + ‘/‘, function (dict) { county = $(‘#county‘); county.empty().append(‘<option value="">请选择区县</option>‘); $.each(dict.data, function (index, item) { county.append(‘<option value=‘ + item[0]+ ‘>‘ + item[1] + ‘</option>‘); }) }) }); }) </script> </head> <body> <select id="pro"> <option value="">请选择省</option> </select> <select id="city"> <option value="">请选择市</option> </select> <select id="county"> <option value="">请选择区县</option> </select> </body> </html>
5.setting.py配置mysql数据库
DATABASES = { ‘default‘: { ‘ENGINE‘: ‘django.db.backends.mysql‘, ‘NAME‘: "area", ‘HOST‘: "127.0.0.1", ‘PORT‘: 3306, ‘USER‘: "root", ‘PASSWORD‘: ‘123456‘, } }
以上是关于django实现省市县三级联动的主要内容,如果未能解决你的问题,请参考以下文章