【问题标题】:Issue with Django recognizing URL passed parameterDjango识别URL传递参数的问题
【发布时间】:2021-03-27 07:58:09
【问题描述】:

我正在学习 Django,但在一些简单的测试和传递 URL 参数方面遇到了问题。这是我的 urls.py:

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', views.home, name='home'),
    path('custnames', views.custnames, name='custnames'),
    path('custdetail/<int:cust_id>/', views.cust_detail, name='cust_detail'),
]

这是我的观点.py

def cust_detail(request, cust_id):
    return HttpResponse('<p>Cust Detail View with cust_id {cust_id}</p>')

当我在浏览器中输入我的 URL 时:http://localhost:8000/custdetail/1/

我的输出是:

Cust Detail View with cust_id {cust_id}

“home”和“custnames”部分似乎工作正常。

关于我在这里做错了什么有什么想法吗? 〜埃德

【问题讨论】:

  • 如果要将变量 str 表示传递给字符串 f'&lt;p&gt;Cust... {cust_id}&lt;/p&gt;',则使用 f 字符串
  • HttpResponse 不是模板,而是 HTTP 响应的包装器,其第一个参数是其内容。您正在传递一个字符串,因此该字符串被放入其中。使用 f 字符串、string.format() 或任何类似的东西将内容替换为变量。

标签: django url django-urls


【解决方案1】:

感谢“minglyu”和“Melvyn”。添加“f”有效。

【讨论】:

    猜你喜欢
    • 2015-10-13
    • 2014-03-22
    • 2021-01-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-09
    相关资源
    最近更新 更多