首先说明一下,发表本文只是我自己对instance这个参数的理解!在写本文之前,自己也百度了一下(说实话,要是有翻墙我都Google了,大家都懂的吧!),结果不理想,这下我把自己在使用instance参数的几个场景说明一下:
- 使用场景一:在实例化modelform的时候传入一个对象给instance
def wiki_edit(request, project_id, wiki_id):
wiki_object = models.WiKi.objects.filter(project_id=project_id, id=wiki_id).first()
if not wiki_object:
url = reverse('wiki', kwargs={"project_id": project_id})
# 反向生成首页地址
return redirect(url)
if request.method =="GET":
form = WikiModelForm(request, instance=wiki_object)
return render(request, 'wiki_edit.html', {'form': form})
form = WikiModelForm(request, data=request.POSTdef wiki_edit(request, project_id, wiki_id):
wiki_object = models.WiKi.objects.filter(project_id=project_id, id=wiki_id).first()
if not wiki_object:
url = reverse('wiki', kwargs={"project_id": project_id})
# 反向生成首页地址
return redirect(url)
if request.method =="GET":
form = WikiModelForm(request, instance=wiki_object)
return render(request, 'wiki_edit.html', {'form': form})
form = WikiModelForm(request, data=request.POST, instance=wiki_object)
if form.is_valid():
# 判断用户是否已经选择了父文章
if form.instance.parent:
form.instance.depth = form.instance.depth + 1
else:
form.instance.depth = 1
# form.instance.project = request.tracer.project#或者project_id
form.instance.project_id = project_id
form.save()
url = reverse('wiki', kwargs={"project_id": project_id})
# 反向生成首页地址
preview = "{0}?wiki_id={1}".format(url, wiki_object.id)
return redirect(preview)
return render(request, 'wiki_edit.html', {'form': form}))
if form.is_valid():
# 判断用户是否已经选择了父文章
if form.instance.parent:
form.instance.depth = form.instance.depth + 1
else:
form.instance.depth = 1
# form.instance.project = request.tracer.project#或者project_id
form.instance.project_id = project_id
form.save()
url = reverse('wiki', kwargs={"project_id": project_id})
# 反向生成首页地址
preview = "{0}?wiki_id={1}".format(url, wiki_object.id)
return redirect(preview)
return render(request, 'wiki_edit.html', {'form': form})
这里我传入一个modelform对象,在我们return返回之后,django默认在生成表单的时候,就会帮我们把该对象对应字段的值显示出来了!
- 使用场景二: 还是刚刚的代码,读者请看到表单验证部分,这里我要做的是进行修改的操作!
form = WikiModelForm(request, data=request.POST, instance=wiki_object)
由于我在这里还是制定了instance为当前的modelform对象,那么我以后所做的就是只是对它进行操作!