我无法让Django urlpatterns
将变量作为变量捕获,而是将其作为设置URL。
urlpatterns的:
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!")
答案 0 :(得分:1)
此网址未正确翻译。
请参阅Request URL: http://localhost:8000/views/productview/%3Cint:product_id%3E/
您可以使用eighter path
或re_path
(类似于url,您可以在其中使用正则表达式,以便在url中使用)。所以将你的urlpatterns改为。
from django.urls import path
urlpatterns = [
path('admin/', admin.site.urls),
path('about/', views.about),
path('views/available_products/', views.available_products),
path('views/productview/<int:product_id>/', views.productview)
]
修改强>
或者如果您真的想使用网址,请使用
url('^views/productview/(?P<product_id>\d+)/$', views.productview)
但使用path
是Django 2.0+方法。同时将url
替换为相同的re_path
。