编辑老师信息的传统实现方式

编辑老师信息
在teacher.html中添加修改编辑连接:
<a href="/edit_teacher/?nid={{ row.tid }}">编辑</a>

在views.py中创建响应函数:
def edit_teacher(request):
    if request.method == "GET":#h指的是初次到页面,并没有提交表单POST信息的时候:
        id = request.GET.get("nid")
        bj = sqlhelper.SqlHelper()
        eacer_info = obj.get_one("select id,name from teacher where id = %s",[nid,])
        lass_id_list = obj.get_list("select class_id from teacher2class wehre teacer_id = %s",[nid,])
        lass_list = obj.get_list("select id,title from class",[]) #所有的班级信息,为编辑做准备
        bj.close()
        eturn render(request,'edit_teacher.html',{
           'teacer_info':teacer_info,
           'class_id_list':class_id_list,
           'class_list':class_list,
        })
    else:
        nid = request.GET.get("nid")
        name = request.POST.get("name")
        class_ids = request.POST.getlist("class_ids")
        obj = sqlhelper.SqlHelper()
        #更新老师表格
        obj.modify("update teacher set name=%s where id = %s",[name,nid])
        #更新老师和班级关系表格
        #方法一:先把老师和班级的对应关系删除再添加。
        #方法二:把老对应关系和新对应关系匹配
        obj.modify("delete from teacher2class where teacer_id = %s",[nid,])
        data_list = []
        for cls_id in class_ids:
            temp = (nid,cls_id)
            data_list.append(temp)
        obj.multiple_modify("insert into teacher2class(teacher_id,class_id) values(%s,%s)",data_list)
    return redirect('/teachers/')

新建edit_teacher.html:
<h1>编辑老师</h1>
<form method="POST" action="/edit_teacher/?nid={{ teacer_info.id }}">
<input type="text" name="name" value="{{ teacher_info.name }}" />
<select multiple size="10" name="class_ids">
    {% for item in class_list %}
    <option value = {{ item.id }}>{{ item.tilte }}</option>
    <% endfor %>
</select>
<input type="submit" value="提交" />
</form>

附加:遍历字典的方法
data_list = []
for cls_id in class_ids:
    temp = (nid,cls_id)
    data_list.append(temp)
试着将上述功能采用map和lamda表达式表示出。

 

上一篇:sqlalchemy操作Mysql


下一篇:python学习----简单权限管理系统