Django:如何在模型中将此变量信息显示到模板中

时间:2013-11-25 06:59:24

标签: python django

我想在模板中显示答案主题和问题。我如何在模板中的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的新手,我只有几周时间学习。

2 个答案:

答案 0 :(得分:0)

模板的值在呈现某些html时由views(通过称为context的内容)传递,而不是由您似乎指示的模型类传递。

这也很有意义,因为模型类只是数据库的模式或表示,而视图是从数据库中检索值(或不是)并创建要呈现的动态内容的函数。

以下是official tutorial关于如何正确执行此操作的链接。

答案 1 :(得分: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))