如果 POST 是嵌套数组,如何使用 request.POST 更新 Django 模型的实例?

发布于 2024-09-27 20:28:55 字数 576 浏览 3 评论 0原文

我有一个提交以下数据的表单:

question[priority] = "3"
question[effort] = "5"
question[question] = "A question"

该数据提交到 URL /questions/1/save,其中 1question.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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

染柒℉ 2024-10-04 20:28:55

您可以使用 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()

You can use a ModelForm to accomplish this. First define the ModelForm:

from django import forms

class QuestionForm(forms.ModelForm):
    class Meta:
        model = Question

Then, in your view:

question = Question.objects.get(pk=id)
if request.method == 'POST':
    form = QuestionForm(request.POST, instance=question)
    form.save()
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文