数据表结构

Snip20171224_1

Django view

from django.views import View
from django.core import serializers
from .models import Region

# GET 获取中国省市区信息
def get_region(request, parent_id=1):
    data = Region.objects.filter(parent_id=parent_id)
    json = serializers.serialize("json", data)
    return HttpResponse(json)
    
# 显示级联地址的视图(传入省份数据)
class MyTest(View):
    template_name = 'users/mytest.html'

    def get(self, request):
        address = Region.objects.filter(parent_id=1)
        return render(request, self.template_name, {'data': address})

Django urls

path('mytest/', views.MyTest.as_view()),
path('get-region/<int:parent_id>', views.get_region, name='get-region'),

模板

<form action="" method="post">
    <select name="province" id="province">
        <option value="">请选择</option>
        {% for region in data %}
        <option value="{{ region.id }}">{{ region.region_name }}</option>
        {% endfor %}
    </select>
    <select name="city" id="city">
        <option value="">请选择</option>
    </select>
    <select name="district" id="district">
        <option value="">请选择</option>
    </select>
</form>

{% load static %}
<script src="{% static 'js/jquery.min.js' %}"></script>
<script>
    $(document).ready(function(){
        $('#province').change(function(){
            $('#city, #district').find("option:not(:first)").remove()
            var region_id = $('#province option:selected').val()
            $.getJSON("/user/get-region/" + region_id, function(data){
                items = []
                $.each(data, function(index, content){
                    items.push("<option value=\"" + content.pk + "\">" 
                        + content.fields.region_name + "</option>")
                })
                $("#city").append(items)
            })
        })
        $("#city").change(function(){
            $('#district').find("option:not(:first)").remove()
            var region_id = $('#city option:selected').val()
            $.getJSON("/user/get-region/" + region_id, function (data) {
                items = []
                $.each(data, function (index, content) {
                    items.push("<option value=\"" + content.pk + "\">"
                        + content.fields.region_name + "</option>")
                })
                $("#district").append(items)
            })
        })
    })
</script>