2013-11-27 133 views
0

我一直在嘗試訪問我的模板中的數據庫,到目前爲止我一直不成功。Django使用模板中的特定模型訪問數據庫

這是我一直在試圖進入我的模型類:

class Questionnaire(models.Model): 
    name = models.CharField(max_length=128) 
    redirect_url = models.CharField(max_length=128, help_text="URL to redirect to when Questionnaire is complete. Macros: $SUBJECTID, $RUNID, $LANG", default="/static/complete.html") 

    def __unicode__(self): 
     return self.name 

    def questionsets(self): 
     if not hasattr(self, "__qscache"): 
      self.__qscache = \ 
       QuestionSet.objects.filter(questionnaire=self).order_by('sortid') 
     return self.__qscache 

    class Meta: 
     permissions = (
      ("export", "Can export questionnaire answers"), 
      ("management", "Management Tools") 
     ) 

這裏是我的views.py的樣子:

def question_list(request): 
    question_info = Questionnaire.objects.all() 

    question_data = { 
     "question_detail" : question_info 
    } 

print question_data 
return render_to_response('questionnaire/templates/quizzes.html', question_data, context_instance=RequestContext(request)) 

,最後我的模板quizzes.html

{% for question in question_detail %} 
<h3>{{ question.name }}</h3> 
{% endfor %} 
+1

恰好是不工作怎麼辦? –

+0

你有HTML和BODY的開始和結束標籤嗎?查看原始輸出(在瀏覽器中按Ctrl-u) – erny

+0

正文和HTML標記全部正常工作我有一個工作模板,唯一不起作用的就是數據不會在我的模板中顯示for循環 – user3019469

回答

0

這樣不簡單嗎?

views.py:

def question_list(request): 
    questions = Questionnaire.objects.all() 
    return render_to_response('questionnaire/templates/quizzes.html',{'questions':questions}, context_instance=RequestContext(request)) 

的.html

{% for question in questions %} 
<h3>{{ question.name }}</h3> 
{% endfor %}