Reputation: 393
I started learn Django (1.11) and I follow Django Tutorials. In this part I should create dynamic view (index method) with template. But after I created template
{% 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>No polls are available.</p>
{% endif %}
and index view that uses template
from django.http import HttpResponse
from django.template import loader
from .models import Question
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))
I've go an Error: *NameError at /polls/ *global name 'latest_question_list' is not defined**
Upvotes: 0
Views: 650
Reputation: 26
Try this one:
...
from django.template import loader
from .models import Question
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))
Upvotes: 1
Reputation: 44
Try this instead:
from django.shortcuts import render
def index(request):
latest_question_list = Question.objects.order_by('-pub_date')[:5]
context = {'latest_question_list': latest_question_list}
return render(request,'polls/index.html',context)
Upvotes: 1