2012-05-11 12 views
0

Djangoのフォームで別のモデルからモデルと質問からフォームのラベルを作成します。は、私は2つのモデルを持っている

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) 

EDIT:私はこのようなフォームを作成している

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 'オブジェクトには' fields '属性がないので – TheNone

+1

" my class " 。スーパーへの呼び出しは最初のものでなければなりません – Goin

関連する問題