gpt4 book ai didi

python - Django:将此行的 urls.py 中的使用 'url' 更改为 'path' (?P.+)

转载 作者:行者123 更新时间:2023-12-01 01:40:14 25 4
gpt4 key购买 nike

我正在使用 django2.0 并希望将 urls.py 的格式从这里转换为

from django.conf.urls import url
from . import views

urlpatterns = [
url(r'^$', views.post_list , name='post_list'),
url(r'^(?P<slug>[\w-]+)/$', views.post_detail, name="detail"),
url(r'^category/(?P<hierarchy>.+)/$', views.show_category, name='category'),
]

类似的东西:

from django.urls import path
from . import views

app_name='home'

urlpatterns = [
path('', views.post_list, name='post_list'),
path(<slug:slug>/, views.post_detail, name="detail"),
path(???),
]

我应该如何以新格式编写最后一行代码。感谢您提供的任何帮助。

最佳答案

documentation指定五个路径转换器:intpathstruuidslug

正则表达式模式.+表示“匹配一个或多个字符”,字符可以是任何内容。因此,完全等效的路径转换器是 path:

path - Matches any non-empty string, including the path separator, '/'. This allows you to match against a complete URL path rather than just a segment of a URL path as with str.

所以你可以这样写:

from django.conf.urls import url
from . import views

urlpatterns = [
path('', views.post_list, name='post_list'),
path('<slug:slug>/', views.post_detail, name="detail"),
path('category/<b><path:hierarchy></b>/', views.show_category, name='category'),
]

如果这种层次结构不需要必须匹配斜杠,那么您可以使用str来代替:

str - Matches any non-empty string, excluding the path separator, '/'. This is the default if a converter isn’t included in the expression.

关于python - Django:将此行的 urls.py 中的使用 'url' 更改为 'path' (?P<hierarchy>.+),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51969077/

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