文章转载于 https://my.oschina.net/u/2723480/blog/702874
现在要实现一个form的添加和编辑,就是说对一个数据库表的操作
def log(request,id=0):
assert isinstance(request, HttpRequest)
if request.method == 'POST':
form = app.forms.LogForm(request.POST)
if form.is_valid():
id = form.data['id']
if id:
model = app.models.ChangeLog.objects.get(id=id)
else:
model = app.models.ChangeLog()
model.serial_number = form.cleaned_data['serial_number']
model.name = form.cleaned_data['name']
model.type = form.cleaned_data['type']
model.remark = form.cleaned_data['remark']
model.save()
id = 0
else:
if id:
form = app.forms.LogForm(instance = app.models.ChangeLog.objects.get(id=id))
else:
form = app.forms.LogForm()
return render(request,'app/log.html',{
'title': '变更记录',
'form': form, #获得表单对象
'data':app.models.ChangeLog.objects.all(),
'id': id
})
重点关注 form = app.forms.LogForm(instance = app.models.ChangeLog.objects.get(id=id))
,通过模型实例化表单,可以实现文章再编辑
网友评论