如果 POST 是嵌套数组,如何使用 request.POST 更新 Django 模型的实例?
我有一个提交以下数据的表单:
question[priority] = "3"
question[effort] = "5"
question[question] = "A question"
该数据提交到 URL /questions/1/save,其中 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 并单独设置每个值,但这对于如此美丽的语言来说似乎过于复杂。
I have a form that submits the following data:
question[priority] = "3"
question[effort] = "5"
question[question] = "A question"
That data is submitted to the URL /questions/1/save where 1
is the question.id
. What I'd love to do is get question #1 and update it based on the POST data. I've got some of it working, but I don't know how to push the POST into the instance.
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()
So, is there anyway to push the QueryDict into the model instance and update each of the fields with my form data?
Of course, I could loop over the POST and set each value individually, but that seems overly complex for such a beautiful language.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以使用 ModelForm 来完成此操作。首先定义 ModelForm:
然后,在您看来:
You can use a ModelForm to accomplish this. First define the ModelForm:
Then, in your view: