繁体   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