我有一个提交以下数据的表单:
question[priority] = "3"
question[effort] = "5"
question[question] = "A question"
该数据已提交至网址/ questions / 1 /保存1
为question.id
。我喜欢做的是得到问题#1并根据POST数据进行更新。我有一些工作,但我不知道如何将POST推入实例。
question = get_object_or_404(Question, pk=id)
question <<< request.POST['question'] # This obviously doesn't work, but is what I'm trying to achieve.
question.save()
那么,无论如何将QueryDict推送到模型实例并使用我的表单数据更新每个字段?
当然,我可以遍历POST并单独设置每个值,但对于这样一种优美的语言来说,这似乎过于复杂。
答案 0 :(得分:23)
您可以使用ModelForm来完成此操作。首先定义ModelForm:
from django import forms
class QuestionForm(forms.ModelForm):
class Meta:
model = Question
然后,在您看来:
question = Question.objects.get(pk=id)
if request.method == 'POST':
form = QuestionForm(request.POST, instance=question)
form.save()