如何在 django url 中捕获包含一个或多个正斜杠的字符串
How one can capture string that contain one or more forward slash in django urls
我的代码是这样的
urls.py:
from django.urls import path
from. import views
app_name ='graduates'
urlpatterns = [
.
.
path('status_detail/<str:id>/', views.status_detail, name='status_detail'),
]
views.py:
def status_detail(request, id):
return HttpResponse(id)
然后我想在我的代码中的某处像这样使用它
<a href=" {% url 'graduates:status_detail' graduate.id %}" class="btn text-secondary "></a>
并且它适用于不包含正斜杠的字符串。
但我想将学生的 id 传递给看起来像这样的网址
A/ur4040/09、A/ur5253/09 等等
请帮我看看我该怎么做
尝试将您的 url 更改为正则表达式:
url(r'^status_detail/(?P<str:id>\w+)/', views.status_detail, name='status_detail')
如果 url
不起作用,因为您有 url 具有相同的结构,请使用 re_path
:
re_path(r'^status_detail/(?P<str:id>\w+)/', views.status_detail, name='status_detail')
别忘了导入 re_path
:
from django.urls import path, re_path, include
希望这能解决您的问题。
我们可以使用 django 中可用的默认路径转换器
path('status_detail/<path:id>/', views.status_detail, name='status_detail'),
path - 匹配任何非空字符串,包括路径分隔符“/”。
我的代码是这样的
urls.py:
from django.urls import path
from. import views
app_name ='graduates'
urlpatterns = [
.
.
path('status_detail/<str:id>/', views.status_detail, name='status_detail'),
]
views.py:
def status_detail(request, id):
return HttpResponse(id)
然后我想在我的代码中的某处像这样使用它
<a href=" {% url 'graduates:status_detail' graduate.id %}" class="btn text-secondary "></a>
并且它适用于不包含正斜杠的字符串。 但我想将学生的 id 传递给看起来像这样的网址 A/ur4040/09、A/ur5253/09 等等
请帮我看看我该怎么做
尝试将您的 url 更改为正则表达式:
url(r'^status_detail/(?P<str:id>\w+)/', views.status_detail, name='status_detail')
如果 url
不起作用,因为您有 url 具有相同的结构,请使用 re_path
:
re_path(r'^status_detail/(?P<str:id>\w+)/', views.status_detail, name='status_detail')
别忘了导入 re_path
:
from django.urls import path, re_path, include
希望这能解决您的问题。
我们可以使用 django 中可用的默认路径转换器
path('status_detail/<path:id>/', views.status_detail, name='status_detail'),
path - 匹配任何非空字符串,包括路径分隔符“/”。