引入js文件
修改settings.py关于静态文件的设置
STATIC_URL = '/static/'STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static'),]
在models.py中定义模型
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 makemigrationspython manage.py migrate
通过workbench向表中填充示例数据
在views.py中编写视图
- index用于展示页面
- getArea1用于返回省级数据
- getArea2用于根据省、市编号返回市、区信息,格式都为字典对象
from django.shortcuts import renderfrom django.http import JsonResponsefrom models import AreaInfodef 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})
在urls.py中配置urlconf
from django.conf.urls import urlfrom . import viewsurlpatterns = [ url(r'^$', views.index), url(r'^area1/$', views.getArea1), url(r'^([0-9]+)/$', views.getArea2),]
主urls.py中包含此应用的url
from django.conf.urls import include, urlfrom django.contrib import adminurlpatterns = [ url(r'^', include('ct1.urls', namespace='ct1')), url(r'^admin/', include(admin.site.urls)),]
定义模板index.html