1

我是 Python/Django 新手,几天来一直面临以下问题。我有 2 个 ModelForms 用于一个模型,这个想法是一个模型的数据将有助于填充第二个的多项选择字段。第二种形式的多项选择字段可以填充,但问题是用户的选择没有得到保存。我已经尝试过save(commit=false)save_m2m()但它并没有解决问题。

模型.py:

class Question(models.Model):
    asker = models.ForeignKey(Student, related_name='asker+')
    suggestedHelpers = models.ManyToManyField(Student, related_name='suggested')
    chosenHelpers = models.ManyToManyField(Student, related_name='chosen')

class QuestionForm(ModelForm):
    class Meta:
        model = Question
        exclude = ('chosenHelpers','suggestedHelpers', 'asker',)

class HelpersForm(ModelForm):
        def suggesthelpers(self, question):
            # populate chosenHelpers field according to data from QuestionForm
        class Meta:
            model = Question
            exclude = ('suggestedHelpers', 'asker', 'questionSubj', 'Qtext',)

视图.py

def askq_page(request):
    question = Question(asker=Student.objects.get(user=request.user))
    if request.method == 'POST':
        form = QuestionForm(request.POST, instance=question)
        if form.is_valid():
            question = form.save()
            # process data
            question.save()
            form2 = HelpersForm(instance=question)
            form2.suggesthelpers(question)
            variables = {'form':form2, 'qid':question.id}
            return render_to_response('choosehelper.html',      variables,context_instance=RequestContext(request))
    else:
        variables = RequestContext(request, {'form': QuestionForm()})
    return render_to_response('askq.html', RequestContext(request, {'form': QuestionForm(instance=question)}))

def choosehelper_page(request, form='', qid=''):
    question = Question.objects.get(id=qid)
    if request.method == 'POST':
        form2 = HelpersForm(request, instance=question)
        # here lies the problem- the data gathered from form2 is not saved i.e. the multiple choices chosen by user are not returned
        if form2.is_valid():
            question = form2.save()
            form2.save_m2m()

            helpers = question.chosenHelpers.all()
            for helper in helpers:
                sentQ = ReceivedQ(question=question)
                sentQ.student = helper
                sentQ.save()

            return render_to_response('questionsent.html', {'helpers': helpers, 'qid':    question.id, 'qtext': q}, context_instance=RequestContext(request))

    else:
        form2 = HelpersForm(instance=question)
        form2.suggesthelpers(question)
    return render_to_response('choosehelper.html', RequestContext(request, {'form': form2,    'qid': qid}))
4

0 回答 0