【问题标题】:Django Urlconf Named Groups String MatchingDjango Urlconf 命名组字符串匹配
【发布时间】:2014-10-17 05:53:33
【问题描述】:

我正在尝试匹配 url 中的两个字符串,但由于我对正则表达式的了解不足,它可能无法正常工作。我想要如下网址:

  • testserver/用户名/
  • testserver/用户名/1234/
  • testserver/用户名/rewards/

用户名将作为 kwarg 传递到 url。这是我所拥有的:

url(r'^(?P<username>[-\w]+)/$', Posts_Index, name="userposts"),
url(r'^(?P<username>[-\w]+)/photos/$', Photo_Index, name="userphotos"),
url(r'^(?P<username>[-\w]+)/rewards/$', Rewards_Index, name="userrewards"),
url(r'^(?P<username>[-\w]+)/following/$', Follower_Index, name="userfollowers"),
url(r'^(?P<username>[-\w]+)/followers/$', Following_Index, name="userfollowing"),
url(r'^(?P<username>[-\w]+)/(?P<pk>\d+)/$', SinglePost_Index, name="singlepost"),

但是,只会找到用户帖子。如果我尝试查询 userphotos 或 userposts 下面的任何内容,则只会检查 userposts url,这显然会导致失败。我该如何解决这个问题?

【问题讨论】:

  • 在奖励网址中最后没有/ 符号。而且要匹配一个或多个数字,您需要使用\d+\d 只匹配一个数字。
  • @AvinashRaj 感谢您发现这一点。当您说奖励网址的最后没有 / 符号时,我假设您正在谈论我列出的所需网址。然后是的。但是在 urlconf 中, / 存在。不过我猜会编辑它。
  • 我认为testserver/ 会自动添加。我说的对吗?
  • @AvinashRaj ,正确,我只关心 testserver 之后会发生什么
  • 请发布整个 urlpatterns 变量

标签: python regex django urlconf


【解决方案1】:

来自django docsDjango runs through each URL pattern, in order, and stops at the first one that matches the requested URL.

因此,如果您颠倒 url 的顺序,它应该会更好。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-09-10
    • 2018-08-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-02-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多