【问题标题】:Django routing issueDjango 路由问题
【发布时间】:2013-09-11 14:58:43
【问题描述】:

我有这条路线:

url(r'^profile/(?P<user_id>\d+)/?(.+)$', Profile.as_view())

问题是当我转到/profile/12345 时,最后一位数字在传递给处理程序时被截断。所以我得到user_id=1234。但是,如果我像我期望的那样去/profile/12345/ 或 /profile/12345/user_namethenuser_id=12345`。有谁知道为什么我的最后一个数字被截断了?

【问题讨论】:

    标签: python django routing


    【解决方案1】:

    您的正则表达式实际上是在捕获 url 的最后一个字符:

    >>> import re
    >>> re.search("(?P<user_id>\d+)/?(.+)", "/profile/12345").groups()
    ('1234', '5')
    >>> re.search("(?P<user_id>\d+)/?(.+)", "/profile/12345/").groups()
    ('12345', '/')
    

    试试更简单的吧:

    url(r'^profile/(?P<user_id>\d+)$', Profile.as_view())
    

    请注意,您实际上不需要在最后处理/(引用来自此answer):

    在没有正斜杠的 Django URLs 中自动有一个正向 斜线附加到它们。这是 Django 开发人员的偏好 而不是网络的硬编码规则(我认为它实际上是一个设置 在 Django 中)。

    另见:

    希望对您有所帮助。

    【讨论】:

      【解决方案2】:

      最后一位数字被.+ 模式捕获。如果你切换到.* 就可以了:

      >>> a = re.compile('profile/(?P<user_id>\d+)/?(.+)')
      >>> s = a.search("/profile/1234")
      >>> s.groups()
      ('123', '4')
      
      >>> a = re.compile('profile/(?P<user_id>\d+)/?(.*)')
      >>> s = a.search("/profile/1234")
      >>> s.groups()
      ('1234', '')
      >>> s.groupdict()
      {'user_id': '1234'}
      

      也请参阅 alecxe 的回答。我不知道你在做什么是一个好的做法。我可能会将其拆分为指向同一视图的两种不同模式。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-10-09
        • 2021-07-24
        • 1970-01-01
        • 2017-03-26
        • 1970-01-01
        • 2018-09-30
        相关资源
        最近更新 更多