从模型创建表单标签,以django形式从另一个模型创建问题

时间:2012-05-11 20:08:51

标签: django django-forms

我有两种模式:

class Questions(models.Model):
  question = models.TextField(verbose_name='Question')
  def get_answers(self):
      query = self.answers.select_related()
      for q in query:
          return q

  def __unicode__(self):
      return u'%s'%(self.question)

class Answers(models.Model):
   answers = models.CharField(verbose_name='answer')
   question = models.ForeignKey(Questions, related_name="answers")

   def __unicode__(self):
       return u'%s'%(self.answers)

我想创建一个表单,该表单形成从问题创建的标签和答案的答案。我创建了一个这样的表单:

class QuestionForm(forms.Form):

    def __init__(self,questions, *args, **kwargs):
        self.questions = questions
        for question in questions:
            field_name = "question_%d" % question.pk
            choices = []
            for answer in question.answers.all():
                choices.append((answer.pk,answer.answers))

            field = forms.ChoiceField(label=question.question, required=True,
                                  choices=choices, widget=forms.RadioSelect)
        return super(QuestionForm, self).__init__(*args, **kwargs)

编辑:

def my_view(request):
    questions = Questions.objects.filter(......)
    form = QuestionForm(questions)
    return render_to_response('my_view.html',
                          {
                            'form':form
                          },
                          context_instance=RequestContext(request))

但是从上面看,模板中没有任何形式。我的QuestionForm出了什么问题?

提前致谢

1 个答案:

答案 0 :(得分:2)

如果您为此更改课程,您的表单将有效

 class QuestionForm(forms.Form):

    def __init__(self,questions, *args, **kwargs):
        super(QuestionForm, self).__init__(*args, **kwargs)
        self.questions = questions
        for question in questions:
            field_name = "question_%d" % question.pk
            choices = []
            for answer in question.answers.all():
                choices.append((answer.pk,answer.answers))

            self.fields[fields_name] = forms.ChoiceField(label=question.question, required=True,
                              choices=choices, widget=forms.RadioSelect)