当前位置:首页 >> 脚本专栏

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

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

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

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

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

Model

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

# 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

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'

{% block admin_change_form_document_ready %}
  <script type="text/javascript"
      id="django-admin-form-add-constants"
      src="/UploadFiles/2021-04-08/change_form.js' %}">

参考: https://www.jb51.net/article/142409.htm

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