且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用 Django 表单编辑模型数据

更新时间:2023-02-15 16:02:34

假设您使用的是 ModelForm,请使用 instance 关键字参数,并传递您使用的模型更新中.

Assuming you are using a ModelForm, use the instance keyword argument, and pass the model you are updating.

因此,如果您有 MyModelMyModelForm(后者必须扩展 django.forms.ModelForm),那么您的代码片段可能看起来像:

So, if you have MyModel and MyModelForm (the latter of which must extend django.forms.ModelForm), then your code snippet might look like:

my_record = MyModel.objects.get(id=XXX)
form = MyModelForm(instance=my_record)

然后,当用户通过POST发回数据时:

And then, when the user sends back data by POST:

form = MyModelForm(request.POST, instance=my_record)

顺便说一下,ModelForm 的文档在这里:http://docs.djangoproject.com/en/1.8/topics/forms/modelforms/

Incidentally, the documentation for ModelForm is here: http://docs.djangoproject.com/en/1.8/topics/forms/modelforms/