我关注DJango tutorial。
return HttpResponse(template.render(context, request))
不会返回民意调查问题,我收到的消息是“没有民意调查可用。”
我完全按照教程,但我无法得到结果。
视图:
def index(request):
latest_question_list=Question.objects.order_by('-pub_date')[:5]
template = loader.get_template('polls/index.html')
context = {
'latest question list': latest_question_list,
}
return HttpResponse(template.render(context, request))
的index.html
{% if latest_question_list %}
<ul>
{% for question in latest_question_list %}
<li><a href="/polls/{{question.id}}/">{{question.question_text}}</a></li>
{% endfor %}
</ul>
{% else %}
<p>why No polls available now</p>
{% endif %}
模型:
class Question(models.Model):
question_text = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')
def __str__(self):
return self.question_text
def was_published_recently(self):
return self.pub_date >= timezone.now() - datetime.timedelta(days=1)
答案 0 :(得分:1)
您在视图中有无效的上下文变量名称,它应该是latest_question_list
而不是latest question list
与模板中的相同:
def index(request):
latest_question_list=Question.objects.order_by('-pub_date')[:5]
template = loader.get_template('polls/index.html')
context = {
'latest_question_list': latest_question_list,
}
return HttpResponse(template.render(context, request))