models.py有
class Question(models.Model):
Question_Id = models.AutoField(primary_key=True)
Question_Text = models.TextField(max_length=1000)
def __str__(self):
return self.Question_Text
def __int__(self):
return self.Question_Id
class QuestionChoices(models.Model):
Choice_Id = models.AutoField(primary_key=True)
Question_Choices_Question_Id = models.ForeignKey("Question", on_delete=models.CASCADE)
Choice = models.TextField(max_length=500)
Is_Right_Choice = models.BooleanField(default=False)
views.py文件具有以下内容
def QuestionDisplay(request):
retrieved_questions_id = Question.objects.values("Question_Id")
retrieved_questions = Question.objects.filter(Question_Id = retrieved_questions_id)
display_content = {retrieved_questions_id: retrieved_questions}
return render(request, 'cgkapp/Question_page.html', context=display_content)
模板文件夹Question_page.html有
{% block body_block %}
<table>
<thead>
<th>Questions</th>
</thead>
{% for quest in display_content %}
<tr>
<td>{{quest.Question_Text}</td>
</tr>
{% endfor %}
</table>
{% endblock %}
该页面将问题显示为表格标题,但不显示模型中的实际问题。可能是什么原因?
答案 0 :(得分:0)
您有拼写错误,在Question_Text}
<td>{{quest.Question_Text}}</td>
评论后更新
如下所示,不知道为什么但我觉得你很困惑。它将解决您的问题
<强> models.py 强>
class Question(models.Model):
# `id` primary key is already present no need to define.
question_text = models.TextField(max_length=1000)
def __str__(self):
return self.question_text
<强> views.py 强>
def question_display(request):
# There is no need of 2 queries, you can get that in single query.
questions = Question.objects.all();
# If you want only question ids
question_ids = Question.objects.values('id')
# You can send multiple variables to the template using context dictionary and directly access them there.
context = {'questions': questions, 'question_ids':question_ids}
return render(request, 'cgkapp/Question_page.html', context)
在模板中
#Show questions with only question texts
<table>
<thead>
<th>Questions</th>
</thead>
{% for quest in questions %}
<tr>
<td>{{quest.question_text}}</td>
</tr>
{% endfor %}
</table>
# If you also want to show question text with ids.
<table>
<thead>
<th>Question ID</th>
<th>Question Text</th>
</thead>
{% for quest in questions %}
<tr>
<td>{{quest.id}}</td>
<td>{{quest.question_text}}</td>
</tr>
{% endfor %}
</table>
# If you want to show only Question IDs
<table>
<thead>
<th>Question ID</th>
</thead>
{% for quest in question_ids %}
<tr>
<td>{{quest}}</td>
</tr>
{% endfor %}
</table>
#This same thing can be done this way also.
<table>
<thead>
<th>Question ID</th>
</thead>
{% for quest in questions %}
<tr>
<td>{{quest.id}}</td>
</tr>
{% endfor %}
</table>
答案 1 :(得分:0)
如果只是拼写错误,您会看到正在呈现的字符串{{quest.Question_Text}
。问题出在您的背景上。你正在那里发送一个字典,其中键应该是字符串,
display_content = {'retrieved_questions_id': retrieved_questions}
然后,在您的模板中,您将迭代retrieved_questions_id
而不是display_content
。 display_content
只是您存储值的字典的名称。