参考链接:
- https://blog.csdn.net/qq_16102629/article/details/81179250
- https://www.cnblogs.com/ttzz/p/10732405.html
- https://blog.csdn.net/qq_34964399/article/details/80998502
1. 确定联动的上下级select 的 id
用浏览器查看源代码就能找到。
2. 用js实现ajax请求
链接2作者在代码中做了标识,但我还是研究了半天才明白个中含义,这里再做一下注释。
在xadmin/static/xadmin/js路径下新建js文件,参照链接2的建议我命名为xadmin.widget.categoryselect.js
代码如下:
$('#id_typeparent').change(function () {
var module = $('#id_typeparent').find('option:selected').val(); //获取父级选中值
$('#id_typeson')[0].selectize.clearOptions();// 清空子级
$.ajax({
type: 'get',
url: '/select/typeparent_typeson/?module=' + module,
data: '',
async: true,
beforeSend: function (xhr, settings) {
xhr.setRequestHeader('X-CSRFToken', '{{ csrf_token }}')
},
success: function (data) {
data = JSON.parse(data.typeson)//将JSON转换
for (var i = 0; i < data.length; i++) {
var test = {text: data[i].fields.type, value: data[i].pk, $order: i + 1}; //遍历数据,拼凑出selectize需要的格式
console.log(test)
$('#id_typeson')[0].selectize.addOption(test); //添加数据
}
},
error: function (xhr, textStatus) {
console.log('error')
}
})
})
注释如下:
红色线是上级id
橙色线是下级id
绿色线第1处我不确定是否必须照此规则命名
绿色线第2处应该是后面view函数里要用到的
蓝色线是下级列表想显示的数据项
3. 将js加入xadmin
在xadmin/widgets.py文件中找到AdminSelectWidget这个类,向里面加入我们的js。
class AdminSelectWidget(forms.Select):
@property
def media(self):
return vendor('select.js', 'select.css', 'xadmin.widget.select.js', 'xadmin.widget.categoryselect.js')
4. 添加view函数和url来引用js
在要实现二级联动的app的views.py中添加函数:
from django.views.generic.base import View
from .models import Typeson
from django.core import serializers
from django.http import JsonResponse
# 二级联动View函数
class SelectView(View):
def get(self, request):
# 通过get得到父级选择项
typeparent_id = request.GET.get('module', '')
# 筛选出符合父级要求的所有子级,因为输出的是一个集合,需要将数据序列化 serializers.serialize()
typesons = serializers.serialize("json", Typeson.objects.filter(typeparent_id=int(typeparent_id)))
# 判断是否存在,输出
if typesons:
return JsonResponse({'typeson': typesons})
参考链接3将函数调整为了SelectView(View)
,不知道链接1和2为什么是SelectView(LoginRequiredMixin, View)
。
在urls.py中添加链接:
from appname.views import SelectView
urlpatterns = [
path('xadmin/', xadmin.site.urls),
path('select/typeparent_typeson/', SelectView.as_view(), name='typeparent_typeson')
]
以上,
只是依葫芦画瓢实现了这个功能。
问题:
上级列表先选择后清除时会报错。