让Django urlpatterns
将一个变量作为一个变量捕获而不是将其作为一个设置URL我遇到了麻烦 .
URL模式:
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^about/', views.about),
url(r'^views/available_products/', views.available_products),
url(r'^views/productview/<int:product_id>/', views.productview)
]
当我托管服务器并转到/ about /,/ views / available_products /或/ admin /它们工作正常,但尝试转到/ views / productview / 1 /会出现404错误,而转到/ views / productview //给出了一个缺失的参数-error .
我试图阅读文档,并没有明确告诉我为什么我的url变量参数不起作用,但显然我做了一些根本错误的事情 .
以下是调试页面中的示例错误消息:
Page not found (404)
Request Method: GET
Request URL: http://localhost:8000/views/productview/12/
Using the URLconf defined in firstdjango.urls, Django tried these URL patterns, in this order:
^admin/
^about/
^views/available_products/
^views/productview/<int:product_id>/
The current path, views/productview/12/, didn't match any of these.
这里是相同的错误消息,但我尝试的URL与urlpatterns中的相同:
TypeError at /views/productview/<int:product_id>/
productview() missing 1 required positional argument: 'product_id'
Request Method: GET
Request URL: http://localhost:8000/views/productview/%3Cint:product_id%3E/
Django Version: 1.11.8
Exception Type: TypeError
Exception Value:
productview() missing 1 required positional argument: 'product_id'
Server time: Sat, 10 Feb 2018 12:25:21 +0000
views.py:
from django.http import HttpResponse, Http404
from django.shortcuts import render
def starting_instructions(request):
return render(request, "webshop/instructions.html", {})
def about(request):
return HttpResponse("about page")
def productview(request, product_id):
"""
Write your view implementations for exercise 4 here.
Remove the current return line below.
"""
return HttpResponse("product {}".format(product_id))
def available_products(request):
"""
Write your view implementations for exercise 4 here.
Remove the current return line below.
"""
return HttpResponse("View not implemented!")
1 回答
此网址未正确翻译 .
见
Request URL: http://localhost:8000/views/productview/%3Cint:product_id%3E/
您可以使用eighter
path
或re_path
(类似于url,您可以在其中使用正则表达式,以便在url中使用) . 所以将你的urlpatterns改为 .EDIT
或者如果你真的想使用url,请使用它
但使用
path
是Django 2.0方法 . 也用re_path
替换url
,这是相同的 .