使用正则表达式时的混乱网址
Messy Urls When Using Regex
我使用的是 django allauth,最初用户可以通过访问 website/profile
来访问他们的个人资料,urls.py 是 path('profile/', include('users.urls'))
。后来我决定让用户查看其他用户的个人资料,因此我想我需要将 urls.py 更改为 path(r'^profile/(?P<user_id>[\w-]+)/$', include('users.urls'))
。
问题是,现在当用户访问个人资料时,不是像 website/profile/user1
这样漂亮、干净的 url,而是像这样 website/%5Eprofile/(%3FP1%5B%5Cw-%5D+)/$
。
这可能不是问题,但我更喜欢我网站地址栏中的干净 url,并认为这可能表明我的实施不正确。
谢谢。
使用 re_path 或 slug 模式
re_path(r'^profile/(?P<user_id>[\w-]+)/$', include('users.urls'))
#or
path('profile/<slug:user_id>/', include('users.urls'))
^
是 %5E
urlencoded 等其他额外字符,
您混淆了旧的正则表达式路径(url()
or re_path()
) with new path()
语法
如果你想保留路径:
path('profile/<username>', include('users.urls'))
如果您需要自定义,也可以检查path converters
或
re_path(r'^profile/(?P<user_id>[\w-]+)/$', include('users.urls'))
我使用的是 django allauth,最初用户可以通过访问 website/profile
来访问他们的个人资料,urls.py 是 path('profile/', include('users.urls'))
。后来我决定让用户查看其他用户的个人资料,因此我想我需要将 urls.py 更改为 path(r'^profile/(?P<user_id>[\w-]+)/$', include('users.urls'))
。
问题是,现在当用户访问个人资料时,不是像 website/profile/user1
这样漂亮、干净的 url,而是像这样 website/%5Eprofile/(%3FP1%5B%5Cw-%5D+)/$
。
这可能不是问题,但我更喜欢我网站地址栏中的干净 url,并认为这可能表明我的实施不正确。
谢谢。
使用 re_path 或 slug 模式
re_path(r'^profile/(?P<user_id>[\w-]+)/$', include('users.urls'))
#or
path('profile/<slug:user_id>/', include('users.urls'))
^
是 %5E
urlencoded 等其他额外字符,
您混淆了旧的正则表达式路径(url()
or re_path()
) with new path()
语法
如果你想保留路径:
path('profile/<username>', include('users.urls'))
如果您需要自定义,也可以检查path converters
或
re_path(r'^profile/(?P<user_id>[\w-]+)/$', include('users.urls'))