【问题标题】:How to have exception for some words - Regex in django url pattern?如何对某些单词有例外 - django url 模式中的正则表达式?
【发布时间】:2019-03-20 02:58:48
【问题描述】:

在我的网站上,人们可以使用https://example.com/slug-profile 之类的网址访问其他人的个人资料,这是模式:

path('<slug:slug>',views.profile,name='profile')

我也希望用户去settings,notifications:

path('settings',views.param,name='param')
# https://example.com/settings

path('notifications',views.notifications,name='notifications')
# https://example.com/notifications

但在这种情况下,settings 将被视为 slug。我已经设置了一个函数来避免用户拥有slug,比如settings或notifications。

我看到一些网站使用前缀或类似的东西

www.example.com/<strong>user</strong>/settings/
www.twitter.com/<strong>i</strong>/notifications/

在我的项目中我会这样做:

re_path(r'^(?P<slug>\w{5,})$',views.profile,name='profile')

path('i/settings',views.param,name='param')

i 或 user 永远不会被视为 slug 配置文件,因为 slug 正则表达式必须至少有 5 个字符。

如何将这些单词或单词列表['settings','notifications'] 作为正则表达式模式中的例外?

或者

我是否需要在 url 中使用包含 i user 的示例?

【问题讨论】:

    标签: python regex django django-urls


    【解决方案1】:

    解决方案比这更简单。只需将您的特定 URL放在首位;由于模式总是按顺序匹配,因此设置和通知将匹配它们自己的路径,而不是 slug 路径。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-09-27
      • 1970-01-01
      • 1970-01-01
      • 2011-10-12
      • 2013-06-16
      • 1970-01-01
      • 2015-06-22
      相关资源
      最近更新 更多