views:

26

answers:

1

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.

+3  A: 

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()
ars
Thanks ars, and `request.POST` is smart enough to ignore the other stuff in there only updating the `request.POST[question]` part of it? Specifically, I don't want it thinking `user[email]` has anything to do with the `Question` object.
Mark Huot
@Mark: The ModelForm will compare the names of your Model fields and form fields, then pull those in. So if your Question model and your web form each have a a field called question, it gets assigned. If your form has a field called email, but there is no such field in the Qeustion model, it won't be assigned. See the linked documentation for more control over this, if you need it (for example, you can exclude field names).
ars