gpt4 book ai didi

python - Django url 变量捕获

转载 作者:太空宇宙 更新时间:2023-11-03 14:08:01 24 4
gpt4 key购买 nike

我在让 Django urlpatterns 将变量捕获为变量并将其作为设置的 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!")

最佳答案

该网址翻译不正确。

请参阅请求 URL:http://localhost:8000/views/productview/%3Cint:product_id%3E/

您可以使用八个pathre_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,请像这样使用

url('^views/productview/(?P<product_id>\d+)/$', views.productview)

但是使用 path 是 Django 2.0+ 的方法。还将 url 替换为 re_path,这是相同的。

关于python - Django url 变量捕获,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48720764/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com