4

我得到了一个如下所示的表单,我希望它在呈现 HTML 时填充来自数据库的信息。我将 Coworker 的 id 作为视图的参数传递。

请参见下面的代码:

视图.py

def EditCoworker(request, id):
    form = FormEditCoworker(Coworkers.objects.get(id=id))
    if request.method == "POST":
        form = FormEditCoworker(request.POST)
        if form.is_valid():
            form.save()
            confirmation_message = "Coworker information updated successfully!"
            return render(request, "coworkers/coworkers.html", locals())
        else:
            return render(request, "coworkers/edit_coworker.html", locals())
    return render(request, 'coworkers/edit_coworker.html', locals())

表格.py

class FormEditCoworker(ModelForm):
    class Meta:
        model = Coworkers

网址.py

url(r'^edit_coworker/(?P<id>[\d]+)$', views.EditCoworker),

当然,我的views.py 中的代码是不对的。

有人可以帮我吗?

提前致谢!

4

1 回答 1

4

这条线

form = FormEditCoworker(Coworkers.objects.get(id=id))

应该

form = FormEditCoworker(instance=Coworkers.objects.get(id=id))

尽管您应该真正处理 Coworker 不存在的情况

form = FormEditCoworker(instance=get_object_or_404(Coworkers, id=id))

编辑:正如 Alisdair 所说,您还应该将实例关键字 arg 传递给绑定表单

instance = get_object_or_404(Coworkers, id=id)
form = FormEditCoworker(instance=instance)
if request.method == "POST":
    form = FormEditCoworker(request.POST, instance=instance)
于 2012-12-17T13:51:15.470 回答