STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static'), ]
class AreaInfo(models.Model): aid = models.IntegerField(primary_key=True) atitle = models.CharField(max_length=20) aPArea = models.ForeignKey('AreaInfo', null=True)
python manage.py makemigrations python manage.py migrate
from django.shortcuts import render from django.http import JsonResponse from models import AreaInfo def index(request): return render(request, 'ct1/index.html') def getArea1(request): list = AreaInfo.objects.filter(aPArea__isnull=True) list2 = [] for a in list: list2.append([a.aid, a.atitle]) return JsonResponse({'data': list2}) def getArea2(request, pid): list = AreaInfo.objects.filter(aPArea_id=pid) list2 = [] for a in list: list2.append({'id': a.aid, 'title': a.atitle}) return JsonResponse({'data': list2})
from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.index), url(r'^area1/$', views.getArea1), url(r'^([0-9]+)/$', views.getArea2), ]
from django.conf.urls import include, url from django.contrib import admin urlpatterns = [ url(r'^', include('ct1.urls', namespace='ct1')), url(r'^admin/', include(admin.site.urls)), ]
'DIRS': [os.path.join(BASE_DIR, 'templates')],
<!DOCTYPE html>
<html>
<head>
<title>省市區列表</title>
</head>
<body>
<select id="pro">
<option value="">請選擇省</option>
</select>
<select id="city">
<option value="">請選擇市</option>
</select>
<select id="dis">
<option value="">請選擇區縣</option>
</select>
</body>
</html>
<script type="text/javascript" src="static/ct1/js/jquery-1.12.4.min.js"></script>
<script type="text/javascript"> $(function(){ $.get('area1/',function(dic) { pro=$('#pro') $.each(dic.data,function(index,item){ pro.append('<option value='+item[0]+'>'+item[1]+'</option>'); }) }); $('#pro').change(function(){ $.post($(this).val()+'/',function(dic){ city=$('#city'); city.empty().append('<option value="">請選擇市</option>'); $.each(dic.data,function(index,item){ city.append('<option value='+item.id+'>'+item.title+'</option>'); }) }); }); $('#city').change(function(){ $.post($(this).val()+'/',function(dic){ dis=$('#dis'); dis.empty().append('<option value="">請選擇區縣</option>'); $.each(dic.data,function(index,item){ dis.append('<option value='+item.id+'>'+item.title+'</option>'); }) }) }); }); </script>