04我们已经实现了新增部门的功能,下面开始修改部门模块的实现。
按道理来说,应该是做成弹框样式的,通过ajax悄咪咪的发数据,然后更新前端数据,但是考虑到实际情况,先用页面跳转的方式实现,后面再用ajax的方式优化一下。
下面开始修改部门的操作。
首先给每一列数据新增一个操作动作,即删除/编辑。
{% extends 'base.html' %}
{% block content %}
<div class="container-fluid">
<div style="margin-bottom: 10px" class="clearfix">
<div class="panel panel-default">
<!-- Default panel contents -->
<div class="panel-heading">
<a class="btn btn-primary" href="/dept/add/" role="button">添加部门</a>
</div>
<div class="panel-body">
<p>部门列表</p>
</div>
<!-- Table -->
<table class="table">
<thead>
<tr>
<th>ID</th>
<th>name</th>
<th>head</th>
<th>phone</th>
<th>email</th>
<th>address</th>
<th>操作</th>
</tr>
</thead>
<tbody>
{% for obj in queryset %}
<tr>
<td>{{ obj.id }}</td>
<td>{{ obj.name }}</td>
<td>{{ obj.head }}</td>
<td>{{ obj.phone }}</td>
<td>{{ obj.email }}</td>
<td>{{ obj.address }}</td>
<td>
<a class="btn btn-success" href="/dept/{{ obj.id }}/edit_detail/" role="button">编辑部门</a>
<a class="btn btn-danger" href="/#" role="button">删除部门</a>
</tr>
{% endfor %}
</tbody>
</table>
</div>
</div>
</div>
{% endblock %}
效果如下:
下面我们来实现编辑的功能
配置URL路径
urlpatterns = [
# 部门管理
path("dept/list/", dept.dept_list),
path("dept/add/", dept.dept_add),
path("dept/<int:nid>/edit_detail/", dept.dept_editdetail),
]
定义dept_editdetail函数
"""修改部门"""
def dept_editdetail(request, nid):
return render(request, 'dept_editdetail.html')
定义dept_editdetail.html
{% extends 'base.html' %}
{% block content %}
<div class="container">
<div class="panel panel-default">
<div class="panel-heading">
<!--title从admin_add()的return返回值中获取,通过模板变量title-->
<h4 class="panel-title">{{ title }}</h4>
</div>
</div>
<div class="panel-body">
<form method="post" action="" novalidate>
<!-- 如果在django中以post 方式提交表单,需要添加csrf_token -->
{% csrf_token %}
{% for field in form %}
<div class="form-group">
<label class="form-control">{{ field.label }}</label>
{{ field }}
<div class="text-danger">{{ field.errors.as_text }}</div>
</div>
{% endfor %}
<button type="submit" class="btn btn-success">保 存</button>
</form>
</div>
</div>
{% endblock %}
重新回到dept_editdetail函数,编写业务逻辑
def dept_editdetail(request, nid):
title = "修改部门"
# 根据id,获取当前数据
row_obj = models.Dept.objects.using('default').get(id=nid)
print("row_obj", row_obj)
# 如果数据不存在,则返回部门列表
if not row_obj:
print("数据不存在")
return redirect('/dept/list')
# 获取表单信息
if request.method == 'GET':
form = DeptEditModelForm(instance=row_obj)
return render(request, 'dept_editdetail.html', {'form': form, 'title': title})
form = DeptEditModelForm(data=request.POST, instance=row_obj)
# print("当前的form", form)
print("form.errors", form.errors)
if form.is_valid():
form.save()
return redirect('/dept/list')
return render(request, 'dept_editdetail.html', {'form': form, 'title': title})
效果如下:
我们舱室修改这条数据的病区名称,从1病区改成10病区试试
发现是可以实现修改的。