简体   繁体   中英

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

I want to display answer subject and question in my template. How would I call these variables from my Answer class in my template?

Here is how my class looks

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) + " "

Template:

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

I am fairly new to Django and I am only a few weeks in to learning.

Values to the template are passed onto by views (through something known as a context ) when they render some html, and not by the model classes as you seem to be indicating.

This also makes sense because model classes are just a schema or a representation of your database, whereas views are functions that retrieve values from the database (or not) and create dynamic content to be rendered.

Here's the link to the official tutorial on how to do it properly.

Pass the values in your views.py something like this:

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))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM