2013-11-25 32 views
0

我想在我的模板中顯示答案主題和問題。我如何從我的模板中的Answer類中調用這些變量?Django:我如何在模型中向模板顯示此變量信息

這裏是我的課怎麼看起來

Model.py:

class Answer(models.Model): 
    subject = models.ForeignKey(Subject, help_text = u'The user who supplied this answer') 
    question = models.ForeignKey(Question, help_text = u"The question that this is an answer to") 
    runid = models.CharField(u'RunID', help_text = u"The RunID (ie. year)", max_length=32) 
    answer = models.TextField() 

    def __unicode__(self): 
     return "Answer(%s: %s, %s)" % (self.question.number, self.subject.surname, self.subject.givenname) 

    def choice_str(self, secondary = False): 
     choice_string = "" 
     choices = self.question.get_choices() 

     for choice in choices: 
      for split_answer in self.split_answer(): 
       if str(split_answer) == choice.value: 
        choice_string += str(choice.text) + " " 

模板:

{{ subject }} 
{{ question }} 
{{ answer }}????? 

我是相當新的Django和我的學習我只有幾個星期。

回答

0

當模板類似於您指示的那樣渲染一些html時,模板值將被views(通過被稱爲context的東西)傳遞到模板類。

這也是有意義的,因爲模型類只是數據庫的模式或表示,而視圖是從數據庫中檢索值(或不是)並創建要呈現的動態內容的函數。

以下是關於如何正確使用official tutorial的鏈接。

0

值傳遞在views.py是這樣的:

from django.shortcuts import render_to_response 

def display_variables(request): 
    subject = # get your subject and assign it a variable 
    question = # get your question and assign it a variable 
    answer = # get your answerand assign it a variable 

    return render_to_response('your_web_page.html',{'subject':subject,'question ':question ,'answer ':answer },context_instance=RequestContext(request)) 
相關問題