Django路由问题

2024-04-29 16:48:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一条路线:

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

问题是,当我转到/profile/12345时,最后一个数字在传递给处理程序时被切断。所以我得到user_id=1234。但是,如果我按我的预期转到/profile/12345/或/profile/12345/user\u name thenuser\u id=12345`的话。有人知道为什么我的最后一个手指被切断了吗?你知道吗


Tags: nameviewidurl处理程序as数字profile
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的答案。我不知道你做的是不是一个好的练习。我可能会把它分成两种不同的模式,指向同一个视图。你知道吗

您的正则表达式实际上捕获了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):

In Django URLs without forward slashes automatically have a forward slash appended to them. This is a preference of the Django developers and not a hard-coded rule of the web (I think it's actually a setting in Django).

另请参见:

希望有帮助。你知道吗

相关问题 更多 >