我定义了一个函数,并尝试在URL中传递两个参数。
运行时会显示错误"not enough arguments for format string"
这是代码 的 views.py
from django.shortcuts import render
# Create your views here.
from django.http import HttpResponse
def detail(request, question_id,choice):
response="You're looking at question %s and choice %s."
return HttpResponse(response % question_id , choice)
urls.py
from django.conf.urls import url
from . import views
urlpatterns = [
url( r'^$', views.index , name='index' ) ,
url( r'^(?P<question_id>[0-9])/(?P<choice>[0-9]+)/$', views.detail , name='detail' ) ,
]
当我通过网址时
http://127.0.0.1:8000/polls/1/2/
错误
TypeError at /polls/1/2/
not enough arguments for format string
如何解决?
答案 0 :(得分:0)
尝试return HttpResponse(response % (question_id, choice))
答案 1 :(得分:0)
使用%
是在python中格式化字符串的旧方法。最好使用.format(..)
,例如
response = "You're looking at question {} and choice {}.".format(question_id, choice)
所以你的代码将是
def detail(request, question_id,choice):
response = "You're looking at question {} and choice {}.".format(question_id, choice)
return HttpResponse(response)
有关详细信息,请查看pyformat.info。