【问题标题】:Django adds an extra "/" in the url?Django 在 url 中添加了一个额外的“/”?
【发布时间】: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 %} &lt;p&gt;{{ instance.id }} - &lt;a href="{{ instance.get_absolute_url }}/"&gt;{{ instance.title }}&lt;/a&gt;&lt;/p&gt; {% endfor %}

标签: python django http-status-code-404


【解决方案1】:

似乎多余的斜线来自您在模板中显示链接的方式

<a href="{{ instance.get_absolute_url }}/">{{ instance.title }}</a>

您可能想尝试删除多余的斜线

<a href="{{ instance.get_absolute_url }}">{{ instance.title }}</a>

作为参考,这是docs中的做法

<a href="{{ object.get_absolute_url }}">{{ object.name }}</a>

【讨论】:

    【解决方案2】:

    您可以根据需要在 settings.py 中添加 APPEND_SLASH = TRUE/FALSE。 当设置为 True 时,如果请求 URL 与您在 urls.py 中提供的任何模式都不匹配,它会附加一个斜杠,并向附加斜杠的同一 URL 发出另一个请求。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-08-14
      • 2021-01-30
      • 2013-01-21
      • 1970-01-01
      • 1970-01-01
      • 2011-08-27
      • 2020-02-25
      • 2015-11-08
      相关资源
      最近更新 更多