As shown in the figure, click a city to display the corresponding school name. At first, I thought it was implemented when I built the data table, but it was implemented through ajax.
Idea: when the get request shows the original state (that is, the drop-down box presents the whole content). After clicking a city, submit it through ajax post, and then the back-end returns the filtered data to the front-end. Then js first deletes all the school labels and creates the school labels from the back-end
views.py
class IndexView(View): def get(self,request): citys = City.objects.all() schools = School.objects.all() return render(request,'index.html',{ 'citys':citys, 'schools':schools, }) def post(self,request): selectCity = request.POST.get('selectVal') schools = City.objects.get(name=selectCity).school_set.all() schoolLists = [ obj.name for obj in schools] schoolDict = dict(zip(schoolLists,schoolLists)) print(schoolLists) return HttpResponse(json.dumps(schoolDict))
Front end
$("#city ul li").on('click',function () { var selectVal = $(this).text(); $("#city button:first").text(selectVal); $.ajax({ type:'POST', url:"{% url 'index' %}", data:{'selectVal':selectVal}, success:function(data) { var len = $("#school li a").length; for(var i=0;i<len;i++){ $("#school li a").eq(0).remove(); } ret = JSON.parse(data); for (var obj in ret) { $("#school ul").append("<li><a>"+ obj +"</a></li>"); } } }) });
The front-end html file is bootstrap, which is roughly
<div id="school" class="dropdown" style="float:left;margin-left:100px"> <button id="i1" class="btn btn-default dropdown-toggle" type="button" id="dropdownMenu1" data-toggle="dropdown" aria-haspopup="true" aria-expanded="true"> //School <span class="caret"></span> </button> <ul class="dropdown-menu" aria-labelledby="dropdownMenu1"> {% for obj in schools %} <li><a href="#" data-value="{{ obj.name }}">{{ obj.name }}</a></li> {% endfor %} </ul> </div> </div>
In this way, you can choose.
2. The following is to realize tag linkage in xadmin, all according to https://blog.csdn.net/qq_16102629/article/details/81179250 Made
The difficulty is how to introduce the custom js file into the registered model.
models.py
class Student(models.Model): name = models.CharField(max_length=10,verbose_name=u'Full name',null=True,blank=True) school = models.ForeignKey(School,verbose_name=u'Student's school',null=True,blank=True) city = models.ForeignKey(City,verbose_name=u'Student city',null=True,blank=True) class Meta: verbose_name = u'Student' verbose_name_plural = verbose_name def __str__(self): return self.name
The customized xadmin.js (name is optional) file is put into extra app / xadmin / static / xadmin / JS, and then the customized xadmin.js file is added in extra app / xadmin / widgets.py. ID city and ID School of JS can be found from the page
$('#id_city').change(function () { var module = $('#id_city').find('option:selected').val(); / / get the parent selected value $('#ID [school ') [0]. Select. Clearoptions(); / / clear child level $.ajax({ type: 'get', url: '/select/city_school/?module=' + module, data: '', async: true, beforeSend: function (xhr, settings) { xhr.setRequestHeader('X-CSRFToken', '{{ csrf_token }}') }, success: function (data) { data = JSON.parse(data.schools)//Convert JSON console.log(data); for (var i = 0; i < data.length; i++) { var test = {text: data[i].fields.name, value: data[i].pk, $order: i + 1}; //Traverse the data and put together the format needed by select console.log(test); $('#ID [school ') [0]. Select. Addoption (test); / / add data } }, error: function (xhr, textStatus) { console.log('error') } }) })
Next, the view function
urlpatterns = [ url(r'select/city_school/',SelectView.as_view(),name='city_school'), ]
from django.core import serializers class SelectView(View): def get(self,request): print("asd") city_id = request.GET.get('module','') schools = serializers.serialize("json", School.objects.filter(school_city_id=int(city_id))) print(schools) # Judge whether it exists, output if schools: return JsonResponse({'schools': schools})