级联下拉的实现方式(如省市县)-1 Smart Selects方式
https://django-smart-selects.readthedocs.io/en/latest/usage.html
特点: 简单,不容易定制,适合简单的关联下拉,只能是table-table
有单选、多选、guoup分组等3种组合
from django.db import models from smart_selects.db_fields import ( ChainedForeignKey, ChainedManyToManyField, GroupedForeignKey, ) class Continent(models.Model): name = models.CharField(max_length=255) def __str__(self): return "%s" % self.name class Country(models.Model): continent = models.ForeignKey(Continent, on_delete=models.CASCADE) name = models.CharField(max_length=255) def __str__(self): return "%s" % self.name class Location(models.Model): continent = models.ForeignKey(Continent, on_delete=models.CASCADE) country = ChainedForeignKey( "Country", chained_field="continent", chained_model_field="continent", show_all=False, auto_choose=True, null=True, blank=True ) city = models.CharField(max_length=50) street = models.CharField(max_length=100)
我在录入location时候, 选择 contient,根据大陆筛选country
关键代码:
class LocationForm(forms.ModelForm): class Meta: model = Location fields = '__all__' def clean(self): cleaned_data = super().clean()
locationCreate.html
{% extends 'appsmarts/base.html' %} {% load crispy_forms_tags %} {% load static %} {% block content %} <form action='.' method='POST'>{% csrf_token %} <script src="{% static 'js/jquery-3.3.1.min.js' %}"></script> <script src="{% static 'smart-selects/admin/js/bindfields.js' %}"></script> <script src="{% static 'smart-selects/admin/js/chainedfk.js' %}"></script> {{ form|crispy}} <input type='submit' value='Save' /> </form> {% endblock %}
js必须放在form tab里面,不知为什么。
smartSelect lib用的js,调用的是google cdb,组好复制到本地,改掉
总之,容易用,但是限制太多 1.只能table-table 2.根据权限不好筛选
以下这个库是辅助录入数据的:
https://github.com/codingjoe/django-select2/tree/main/example/example