【发布时间】:2021-10-28 02:28:31
【问题描述】:
Page not found (404)
Request Method: GET
Request URL: http://127.0.0.1:8000/products/1//
Using the URLconf defined in products.urls, Django tried these URL patterns, in this order:
[name='home']
contact/
admin/
products/ [name='product-list']
products/
products/ <int:id>/ [name='product-detail']
products/ <int:id>/delete/ [name='product-delete']
products/
about/
The current path, products/1//, didn’t match any of these
为什么在 id 后面需要一个额外的斜杠?我处理的越多,它想要的斜线就越多。我有这样的 urls.py:
from django.urls import path
from .views import (
product_detail_view,
product_create_view,
render_initial_data,
dynamic_lookup_view,
product_delete_view,
product_list_view)
app_name = 'product'
urlpatterns = [
path('', product_list_view, name='product-list'),
path('', product_create_view),
path('<int:id>/', dynamic_lookup_view, name='product-detail'),
path('<int:id>/delete/', product_delete_view, name='product-delete'),
path('', product_detail_view),
]
还有另一个 urls.py 类似这样的:
urlpatterns = [
path('', home_view, name='home'),
path('contact/', contact_view),
path('admin/', admin.site.urls),
path('products/', include('product.urls')),
path('about/', about_view),
]
函数如下:
def dynamic_lookup_view(request, id):
#obj = Product.objects.get(id=id)
#obj = get_object_or_404(Product, id=id)
try:
obj = Product.objects.get(id=id)
except Product.DoesNotExist:
raise Http404
context = {
'object': obj
}
return render(request, "products/product_detail.html", context)
所以它引发了异常,因为它正在寻找额外的“/”,但它是从哪里来的?
product_list.html 有这个:
{% for instance in object_list %}
<p>{{ instance.id }} - <a href="{{ instance.get_absolute_url }}/">{{ instance.title }}</a></p>
{% endfor %}
【问题讨论】:
-
你确定你没有访问过
http://127.0.0.1:8000/products/1//吗?您能否验证您是否真的访问过http://127.0.0.1:8000/products/1/?或者只是http://127.0.0.1:8000/products/1? -
@NielGodfreyPonciano 当我访问它时,我得到了错误的列表。 product_list 看起来像这样:
{% for instance in object_list %} <p>{{ instance.id }} - <a href="{{ instance.get_absolute_url }}/">{{ instance.title }}</a></p> {% endfor %}
标签: python django http-status-code-404