自动填充ModelForm,数据已存储在数据库中

时间:2012-12-17 13:13:16

标签: django django-models django-forms

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

见下面的代码:

view.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())

forms.py

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

urls.py

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

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

有人可以帮我吗?

提前致谢!

1 个答案:

答案 0 :(得分: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)