一、set_teachers.py文件
from django.shortcuts import render,redirect from app01 import models def set_teachers(request): if request.method == "GET": nid = request.GET.get("nid") # 获取后可继续传给HTML文件 cls_obj = models.Classes.objects.filter(id=nid).first() cls_teachers_list = cls_obj.c_to_t.all().values_list("id") # 2、先用value_list取出,再用zip函数 id_list = list(zip(*cls_teachers_list))[0] if list(zip(*cls_teachers_list)) else [] # 如果if list(zip(*cls_teachers_list))不为空则执行if前语句,为空时执行else语句 all_teachers_list = models.Teachers.objects.all() # [obj,obj,obj] # 1、可以直接用Queryset类型里对象判断 # for i in all_teachers_list: # if i in cls_teachers_list return render(request,"set_teachers.html",{ "cls_teachers_list": cls_teachers_list, "all_teachers_list": all_teachers_list, "id_list":id_list, "nid":nid }) elif request.method == "POST": nid = request.GET.get("nid") ids = request.POST.getlist("teacher_ids") # 获取多个值 obj = models.Classes.objects.filter(id=nid).first() obj.c_to_t.set(ids) # 重置 return redirect("/classes.html")
二、HTML文件操作
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form action="/set_teachers.html?nid={{nid}}" method="POST"> {% csrf_token %} <select name="teacher_ids" id="" multiple size="10"> {# 设置为多选和大小 #} {% for item in all_teachers_list %} {# 列出所有老师,并通过if判断来默认选择 #} {% if item.id in id_list %} <option value="{{item.id}}" selected="selected">{{item.name}}</option> {% else %} <option value="{{item.id}}" >{{item.name}}</option> {% endif %} {% endfor %} </select> <input type="submit" value="提交"> </form> </body> </html>
三、展示的HTML中代码
<td> {% for item in row.c_to_t.all %} {# 执行函数不用加括号,自动加 #} <span>{{item.name}}</span> {% endfor %} </td>
总结:
关键点在于值的传送与获取,一般传ID,因为其唯一性
原文地址:https://www.cnblogs.com/Lujun1028/p/9577492.html
时间: 2024-11-11 10:08:25