【问题标题】:Not able to pass the two parameters in url无法在 url 中传递两个参数
【发布时间】:2017-11-11 21:24:04
【问题描述】:

我定义了一个函数,并试图在 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

如何解决?

【问题讨论】:

    标签: python django


    【解决方案1】:

    使用% 是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 了解更多信息。

    【讨论】:

    • 当与类似的 def 详细信息( request , question_id ,choice )一起使用时: response = "You're looking at question {} and choice {}.".format(question_id , choice ) return HttpResponse (response % (question_id , choice) ) 引发的错误说“并非所有参数都在字符串格式化期间转换”
    • 对不起,format 的使用代替了% 的使用。我已经更新了我的答案以显示完整的示例。
    • 当任何解决方案满足您的要求时,您应该通过勾选答案@Ishaan Gupta 旁边的复选标记来接受它作为您选择的答案。这就是您如何表达感激之情并感谢该答案的所有者。谢谢。
    • 感谢您的建议,因为我不知道。
    【解决方案2】:

    试试return HttpResponse(response % (question_id, choice))

    【讨论】:

      猜你喜欢
      • 2018-12-22
      • 2021-07-04
      • 1970-01-01
      • 2022-01-25
      • 2012-08-26
      • 1970-01-01
      • 1970-01-01
      • 2019-05-19
      • 1970-01-01
      相关资源
      最近更新 更多