学习了静以修身养心的运维平台开发的代码,对views.py做了下小修改
原文:http://blog.csdn.net/alex_chen_16/article/details/50850435
def lists(request, table):
#从根据不同的请求,来获取相应的数据,并跳转至相应页面
lists = {'node': Node, 'line': Line, 'device': Device}
list_template = {'node': 'node_list.html',
'line': 'line_list.html', 'device': 'device_list.html'}
if table in ['node', 'line', 'device']:
data = lists[table].object.all()
#建立context字典,将值传递到相应页面
context = {
'data': data,
}
#跳转到相应页面,并将值传递过去
return render(request,list_template[table],context)
def add(request, table):
#根据提交的请求不同,获取来自不同Form的表单数据
tables = {'node': NodeForm, 'line': LineForm, 'device': DeviceForm}
signers = {'node': node_signer, 'line': line_signer, 'device': device_signer}
if request.method == 'POST':
form = tables[table](request.POST)
#判断form是否有效
if form.is_valid():
#创建实例,需要做些数据处理,暂不做保存
instance = form.save(commit=False)
#将登录用户作为登记人
instance.signers[table] = request.user
#保存该实例
instance.save()
#跳转至列表页面,配合table参数,进行URL的反向解析
return redirect('lists', table=table)
else:
form = tables[table]()
#创建context来集中处理需要传递到页面的数据
context = {
'form': form,
}
#如果没有有效提交,则仍留在原来页面
return render(request, 'add.html', context)