修改 views.py
@auth
def edit_teacher(request, nid):
if request.method == "get":
obj = models.teacher.objects.get(id=nid)
# 执行后返回元组,每个元组包含传递给values_list() 调用的字段的值
# obj_cls_list = obj.cls.all().values_list('id')
# 把元组中的第一个字段取出,组成列表
# id_list = list(zip(*obj_cls_list))[0]
# 通过 values_list 函数中直接设置 flat=true 返回列表
id_list = obj.cls.all().values_list('id', flat=true).order_by('id')
# print(id_list)
cls_list = models.classes.objects.all()
return render(request, 'edit_teacher.html', {'obj': obj, 'id_list': id_list, 'cls_list': cls_list})
elif request.method == "post":
name = request.post.get('name')
cls_li = request.post.getlist('cls')
# 更新操作
obj = models.teacher.objects.get(id=nid)
obj.name = name
obj.save()
obj.cls.set(cls_li)
return redirect('/teacher.html')
添加 edit_teacher.html
{% extends "layout.html" %}
{% block css %}
{% endblock %}
{% block content %}
编辑老师
老师姓名:
班级:
{% for row in cls_list %}
{% if row.id in id_list %}
{{ row.caption }}
{% else %}
{{ row.caption }}
{% endif %}
{% endfor %}
{% endblock %}
{% block js %}
$(function () {
$('#menu_teacher').addclass('active');
})
{% endblock %}
修改 teacher.html
{% extends "layout.html" %}
{% block css %}
.tag{
display: inline-block;
padding: 5px;
border: 1px solid red;
background-color: lightpink;
cursor: pointer;
}
{% endblock %}
{% block content %}
老师列表
{% for dic in teacher_list.values %}
{{ dic.nid }}{{ dic.name }}{% for c in dic.cls_list %}
{{ c.caption }}
{% endfor %}
{% endfor %}
{% endblock %}
{% block js %}
$(function () {
$('#menu_teacher').addclass('active');
})
{% endblock %}
修改 urls.py
# 注意这里需要 import re_path 来试用正则表达式
from django.urls import path, re_path
urlpatterns = [
# 添加下面几个
path('teacher.html', views.handle_teacher),
path('add_teacher.html', views.add_teacher),
re_path('edit_teacher-(\d+).html', views.edit_teacher),
]
希望与广大网友互动??
点此进行留言吧!