【问题标题】:How one can capture string that contain one or more forward slash in django urls如何在 django url 中捕获包含一个或多个正斜杠的字符串
【发布时间】:2021-09-15 22:55:12
【问题描述】:

我的代码是这样的

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

请帮帮我,我该怎么做

【问题讨论】:

    标签: python django django-urls


    【解决方案1】:

    尝试将您的网址更改为正则表达式:

    url(r'^status_detail/(?P<str:id>\w+)/', views.status_detail, name='status_detail')
    

    如果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
    

    我希望这能解决你的问题。

    【讨论】:

    • 感谢您展示可能的方式。但它不工作还显示错误raise ImproperlyConfigured( django.core.exceptions.ImproperlyConfigured: "^detail/(?P&lt;str:id&gt;\w+)/" is not a valid regular expression: bad character in group name 'str:id' at position 12
    • 我的错,网址上的正则表达式的结构是:(?Ppattern) 所以在这种情况下可能有效:url(r'^status_detail/(?P&lt;id&gt;\w+)/', views.status_detail, name='status_detail')
    【解决方案2】:

    我们可以使用 django 中提供的默认路径转换器

    path('status_detail/<path:id>/', views.status_detail, name='status_detail'),
    

    path - 匹配任何非空字符串,包括路径分隔符“/”。

    【讨论】:

      猜你喜欢
      • 2012-06-29
      • 2015-10-17
      • 2012-06-28
      • 1970-01-01
      • 1970-01-01
      • 2011-04-25
      • 2013-08-11
      • 1970-01-01
      • 2020-08-14
      相关资源
      最近更新 更多