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

时间:2022-09-01 07:24:34

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.

该数据提交到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()

So, is there anyway to push the QueryDict into the model instance and update each of the fields with my form data?

那么,无论如何将QueryDict推送到模型实例并使用我的表单数据更新每个字段?

Of course, I could loop over the POST and set each value individually, but that seems overly complex for such a beautiful language.

当然,我可以遍历POST并单独设置每个值,但对于这样一种优美的语言来说,这似乎过于复杂。

1 个解决方案

#1


22  

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

您可以使用ModelForm来完成此任务。首先定义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()

#1


22  

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

您可以使用ModelForm来完成此任务。首先定义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()