2012-05-11 82 views
0

另一個模型從創建模型和問題表單標籤我有兩個型號:從Django的形式

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來自哪裏?

在此先感謝

+0

什麼是「沒有任何形式的模板」是什麼意思?發佈您的查看代碼。 –

+0

@ChrisPratt;我編輯了我的問題。謝謝 – TheNone

+0

你的意思是說'form'在模板中是未定義的嗎?也許你應該發佈你的模板;)。 –

回答

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) 
+1

+1漂亮。我甚至沒有注意到他沒有實際添加字段到'self.fields' –

+0

我們不能,因爲''QuestionForm'對象沒有'字段'屬性 – TheNone

+1

請更改「你的班級」的「我的班級」 。超級電話應該是第一個 – Goin