簡體   English   中英

Django:如何在我的模板的模型中顯示此變量信息

[英]Django: How do I display this variable information in models to my template

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

這是我班的樣子

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相當陌生,而且我只有幾周的學習時間。

模板的值在呈現某些html時由視圖 (通過稱為context某種東西)傳遞給視圖 ,而不是由您似乎指示的模型類傳遞。

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

這是有關如何正確執行官方教程的鏈接。

像這樣傳遞您的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))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM