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.
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With