Django Admin实现三级联动的示例代码(省市区)

时间:2022-03-02 11:23:01

通过自定义admin的模板文件实现省市区的三级联动.要求创建记录时,根据省>市>区的顺序选择依次显示对应数据.

修改记录时默认显示已存在的数据.

Django Admin实现三级联动的示例代码(省市区)

Django Admin实现三级联动的示例代码(省市区)

model

?
1
2
3
4
5
6
7
8
9
10
11
class member(models.model):
  name = models.charfield(max_length=100, verbose_name='姓名')
  province = models.charfield(max_length=100, null=true, blank=true, verbose_name='省份')
  city = models.charfield(max_length=100, null=true, blank=true, verbose_name='城市')
  district = models.charfield(max_length=100, null=true, blank=true, verbose_name='区/县')
 
  class meta:
    verbose_name_plural = verbose_name = '人员'
 
  def __str__(self):
    return self.name

view和url

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# views
location = {'吉林省': {'长春市': ['南关区', '朝阳区', '二道区', '绿园区']}}
 
 
def choose_province(request):
  province = list(location.keys())
  return jsonresponse(province, safe=false)
 
 
def choose_city(request):
  province = request.get.get('p')
  cities = list(location[province].keys())
  return jsonresponse(cities, safe=false)
 
 
def choose_district(request):
  province = request.get.get('p')
  city = request.get.get('c')
  districts = location[province][city]
  return jsonresponse(districts, safe=false)
  
# urls
from person.views import choose_province, choose_city, choose_district
 
urlpatterns = [
  path('province/', choose_province),
  path('city/', choose_city),
  path('district/', choose_district),
  path('admin/', admin.site.urls),
]

admin

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
class memberform(forms.modelform):
  class meta:
    widgets = {
      'province': forms.select(),
      'city': forms.select(),
      'district': forms.select()
    }
 
@admin.register(member)
class memberadmin(admin.modeladmin):
  form = memberform
  fields = ('name', ('province', 'city', 'district'))
  list_display = ('name', 'province', 'city', 'district')
  change_form_template = 'area.html'

这里需要写一个form将省市区这三个字段显示为单选框.

模板文件

找到django源码中的change_form.html(django/contrib/admin/templates/admin/)文件,复制到app下templates目录中.

在admin中指定自定义的模板文件 change_form_template = 'area.html'

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
{% block admin_change_form_document_ready %}
  <script type="text/javascript"
      id="django-admin-form-add-constants"
      src="{% static 'admin/js/change_form.js' %}"
      {% if adminform and add %}
        data-model-name="{{ opts.model_name }}"
      {% endif %}>
  </script>
 
  <script type="text/javascript">
    (function($) {
      $('#id_city').change(function() {
        let p_id = $('#id_province').val();
        let c_id = $('#id_city').val();
        $.get('/district/', {"p": p_id, "c": c_id }, function(a_info) {
          var area_info = $('#id_district').empty().append('<option value>' + '---------' + '</option>');
          $.each(a_info, function(i, area) {
            area_info.append('<option value="' + area + '">' + area + '</option>')
          });
          {% if change %}
            $("#id_district").find("option:contains({{ original.district }})").attr('selected', true);
          {% endif %}
        });
      });
 
      $('#id_province').change(function() {
        let p_id = $('#id_province').val();
        $.get('/city/', { 'p': p_id }, function(c_info) {
          var city_info = $('#id_city').empty().append('<option value>' + '---------' + '</option>');
          $.each(c_info, function(i, city) {
            city_info.append('<option value="' + city + '">' + city + '</option>')
          });
          {% if change %}
            $("#id_city").find("option:contains({{ original.city }})").attr('selected', true);
            $("#id_city").trigger("change");
          {% endif %}
        });
      });
 
      $.get('/province/', function(p_info) {
        var province_info = $('#id_province').empty().append('<option value>' + '---------' + '</option>');
        $.each(p_info, function(i, province) {
          province_info.append('<option value="' + province + '">' + province + '</option>')
        });
        {% if change %}
          $("#id_province").find("option:contains({{ original.province }})").attr('selected', true);
          $("#id_province").trigger("change");
        {% endif %}
      });
    })(django.jquery);
  </script>

 

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。

原文链接:http://www.cnblogs.com/thunderLL/p/9210472.html