Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I update an instance of a Django Model with request.POST if POST is a nested array?

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.

like image 579
Mark Huot Avatar asked Oct 15 '10 20:10

Mark Huot


1 Answers

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()
like image 180
ars Avatar answered Oct 04 '22 16:10

ars