如何使用Django表单编辑模型数据
我刚开始学习Django,所以对我的新手问题感到抱歉。
我有一个模型,想让用户通过Django表单或者其他方式来编辑里面的数据。
看看上面的图片,我想显示一个已经填好数据的表单,让用户可以更新这些数据。
请问这样做的最好方法是什么?
编辑:这是我的views.py代码。
def exam_Edit(request,examName,number=0):
numner = int(number)
number = int(number)
questionNo = int(numner)
Myexam = models.Exam.objects.get(name = examName)
QuestionsAll = models.Question.objects.filter(exam = Myexam)
myQeustion = Question.objects.filter(exam = Myexam)[nextQuestion]
answer1 = models.Asnwers.objects.filter(question=myQeustion)[0]
answer2 = models.Asnwers.objects.filter(question=myQeustion)[1]
answer3 = models.Asnwers.objects.filter(question=myQeustion)[2]
answer4 = models.Asnwers.objects.filter(question=myQeustion)[3]
# HERE IS MY PROBLEM : the line below creates a form with a data but it doesn't save it to the save object
form = QuestionsEditForm(initial = {'questionText':myQeustion.__unicode__() , 'firstChoiceText':answer1.__unicode__(),'secondChoiceText':answer2.__unicode__(),'thirdChoiceText':answer3.__unicode__(),'forthChoiceText':answer4.__unicode__()})
if request.method =='POST':
#if post
if form.is_valid():
questionText = form.cleaned_data['questionText']
Myexam = Exam.objects.get(name = examName)
myQeustion.questionText = form.cleaned_data['questionText']
answer1.answerText = form.cleaned_data['firstChoiceText']
answer1.save()
answer2.answerText = form.cleaned_data['secondChoiceText']
answer2.save()
answer3.answerText = form.cleaned_data['thirdChoiceText']
answer3.save()
answer4.answerText = form.cleaned_data['forthChoiceText']
answer4.save()
variables = RequestContext(request, {'form':form,'examName':examName,'questionNo':str(nextQuestion)})
return render_to_response('exam_edit.html',variables)
请帮帮我。
1 个回答
68
假设你正在使用一个叫做 ModelForm
的东西,你需要用到一个叫 instance
的参数,把你想要更新的模型传进去。
比如说,你有一个模型叫 MyModel
和一个表单叫 MyModelForm
(这个表单需要继承自 django.forms.ModelForm
),那么你的代码可能看起来像这样:
my_record = MyModel.objects.get(id=XXX)
form = MyModelForm(instance=my_record)
然后,当用户通过 POST 方式发送数据回来时:
form = MyModelForm(request.POST, instance=my_record)
顺便提一下,关于 ModelForm
的详细说明可以在这里找到: http://docs.djangoproject.com/en/1.8/topics/forms/modelforms/