1.需求:编辑班级,难点:点击编辑按钮后,页面如何显示 待编辑 班级的信息(用Form实现), 以及Url 设置
2 url
url(r'^edit_class/nid=(?P<nid>d+)$', views.edit_class),
3 class_list.html里面设置编辑a标签
<a href="/app01/edit_class/nid={{ item.id }}" class="glyphicon glyphicon-pencil">编辑</a>|
# 注意, href必须和url匹配
详细如下
<table class="table table-striped table-bordered table-hover table-condensed"> <thead> <tr> <th>班级ID</th> <th>班级名称</th> <th>操作</th> </tr> </thead> <tbody> {% for item in class_list %} <tr> <td>{{ item.id }}</td> <td>{{ item.title }}</td> <td> <a href="/app01/edit_class/nid={{ item.id }}" class="glyphicon glyphicon-pencil">编辑</a>| <a href="/app01/del_class/nid={{ item.id }}" class="glyphicon glyphicon-trash">删除</a> </td> {#点击删除是一个get请求,要想告诉服务器id,可以通过url get请求获取,或者url匹配到传递给视图#} </tr> {% endfor %} </tbody> </table>
4 视图
def edit_class(request, nid): if request.method == "GET": current_class = models.Classes.objects.filter(id=nid).first() # current_class不能直接传给ClassForm, 必须是字典 obj = ClassForm(initial={'title': current_class.title}) # 初始值显示不会验证数据 # obj = ClassForm(data={'title': current_class.title}) # 不仅会显示数据,而且会进行数据检验 return render(request, 'app01_edit_class.html', {'nid':nid, 'obj': obj}) else: obj = ClassForm(data=request.POST) if obj.is_valid(): # 更新数据库数据 models.Classes.objects.filter(id=nid).update(**obj.cleaned_data) return redirect('/app01/classes') else: return render(request, 'app01_edit_class.html', {'nid':nid, 'obj': obj})
5 模板
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h4>编辑班级</h4> <form action="/app01/edit_class/nid={{ nid }}" method="POST"> {% csrf_token %} {{ obj.title }} {{ obj.errors.title.0 }} <p><input type="submit" value="提交"></p> </form> </body> </html>