代码之家  ›  专栏  ›  技术社区  ›  Scott Skiles

在Django模板中进行路由时,如何处理标题中的正斜杠“/”?

  •  0
  • Scott Skiles  · 技术社区  · 6 年前

    My URL.py和template.html如下所示:

    url.py

    path('item/<str:title>/', views.ItemDetail.as_view(), name="item_detail'),
    

    <h3>Title: <a href="{% url 'item_detail' object.title %}">object.title</a></h3> 
    

    现在,我并不阻止用户创建带有正斜杠的对象。这可能是另一个问题

    在用户创建一个带有正斜杠的项目之后,比如说 'Do 1/2 the work up front' ,如何使用该标题发送到该项目?现在我不知道如何处理正斜杠 / 我得到了一个错误:

    未找到带有参数“(“提前做1/2的工作”)的“项目详细信息”的相反项。尝试了1个模式: ['item\/(?P[^/]+)$']

    我调查 striptags 但那不是我需要的。

    1 回复  |  直到 6 年前
        1
  •  1
  •   Bidhan Majhi    6 年前

    在django str中,除了 /

    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.

    不过,我建议您添加一个slug字段,它会将您的url转换为 this-is-your-url