No polls available!

I am learning django with its own tutorial. When I go to /polls url, I see message No polls available!, but if I go to /polls/1 or /polls/2 I can see the quesions. My files’ contents:

from django.db import models
from django.utils import timezone
import datetime

class Question(models.Model):
    question_text = models.CharField(max_length=200)
    pub_date = models.DateTimeField('date published')

    def recently_published(self):
        now =
        return now - datetime.timedelta(days=1) <= self.pub_date <= now

    def __str__(self):
        return f"{self.question_text}"

class Choice(models.Model):
    question = models.ForeignKey(Question, on_delete=models.CASCADE)
    choice_text = models.CharField(max_length=20)
    votes = models.IntegerField(default=0)

    def __str__(self):
        return f"{self.choice_text}-{self.votes}-{self.question}"

from django import template
from django.http import HttpResponse, Http404, HttpResponseRedirect
from .models import Question, Choice
from django.template import loader
from django.shortcuts import render, get_object_or_404
from django.urls import reverse
from django.views import generic

    Generic views: A shortcut for get data - render data - return data

class IndexView(generic.ListView): # ListView: Display a list of objects
    template_name = 'polls/index.html' # Default template: <app name>/<model name>_list.html
    context_obj_name = 'latest_question_list' # Default: question_list

    def get_queryset(self): # Use this for the list of objects to be displayed
        """Return the last five published questions."""
        return Question.objects.order_by('-pub_date')[:5]

class DetailView(generic.DetailView): # DetailView: Display detail of a special object
    model = Question
    template_name = 'polls/detail.html' # Default template: <app name>/<model name>_detail.html

class ResultView(generic.DetailView):
    model = Question
    template_name = 'polls/results.html'

def vote(request, question_id): # This function has race condition. For more info:
    question_text = Question.objects.get(pk=question_id)
        selected_choice = question_text.choice_set.get(pk=request.POST['choice'])
    except (KeyError, Choice.DoesNotExist):
        # Redisplay the question voting form.
        return render(request, 'polls/detail.html', {
            'question': question_text,
            'error_message': "You didn't select a choice.",
        selected_choice.votes += 1
        return HttpResponseRedirect(reverse('polls:results', args=(question_id,))) # Redirect after POST to results
from django.urls import path
from . import views

app_name = 'polls' # We need to add this for namespacing to separate the file from others.
urlpatterns = [
    path('', views.IndexView.as_view(), name='index'),
    path('<int:pk>/', views.DetailView.as_view(), name="detail"), # Name is used in {% url %}
    path('<int:pk>/results/', views.ResultView.as_view(), name="results"),
    path('<int:question_id>/vote/',, name="vote"),

What is the problem?

What does your polls/index.html template look like?

{% if latest_question_list %}
    {% for question in latest_question_list %}
        <li><a href="/polls/{{ }}/">{{ question.question_text }}</a></li> <!-- We can use '<li><a href="{% url 'polls:detail' %}">{{ question.question_text }}</a></li>' instead -->
    {% endfor %}
{% else %}
    <p>No polls available!</p>
{% endif %}

Review Making friendly template contexts regarding the identification of the context variable.

1 Like