Views.py and Urls.py not rendering properly

Building your first Django app Part 2 has us add more views to our polls/views.py which takes a string specifier and replaces it with values from question_id which is given to the function as a parametre.

The issue here is, I get the string as it is in views.py with the %s placeholder still there like so

You are looking at the results of question %s

Below are my views and urls.py code snippet

Views.py

from django.shortcuts import render
from django.http import HttpResponse
from .models import Question
from django.template import loader


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

def detail(request, question_id):
    return HttpResponse("You are looking at %s ", question_id)

def results(request, question_id):
    response = "You are looking at the results of question %s "
    return HttpResponse(response, question_id)

def vote(request, question_id):
    return HttpResponse("You are voting on question %s ", question_id)

Urls.py

from django.urls import path

from . import views


urlpatterns = [

    # ex: polls
    path('', views.index, name='index'),

    # ex: polls/5/detail
    path('<int:question_id>/', views.detail, name='detail'),

    # ex: polls/5/results
    path('<int:question_id>/results/', views.results, name='results'),

    # ex: polls/5/vote
    path('<int:question_id>/vote/', views.vote, name='vote'),

The issue is that you’re passing the value for formatting string as an argument to HttpResponse. You need to do the following instead:

return HttpResponse("You are looking at %s " % question_id)

You can also use template strings with python 3.5+:

return HttpResponse(f"You are looking at {question_id}")
1 Like

Thanks for this, it was obviously an oversight because it (the percent sign) was added in the tutorial and I was just too carried away to have thought about it.