如何使用Django窗体编辑模型数据?

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (1)
  • 关注 (0)
  • 查看 (48)

我有一个模型,我需要让用户使用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)               

请帮忙

提问于
用户回答回答于

假设使用的是ModelForm,使用instance关键字参数,并传递要更新的模型。

所以,如果你有MyModelMyModelForm(后者必须延长django.forms.ModelForm),那么代码片段看起来可能如下所示:

my_record = MyModel.objects.get(id=XXX)
form = MyModelForm(instance=my_record)

然后,当用户通过POST发回数据时:

form = MyModelForm(request.POST, instance=my_record)

扫码关注云+社区