【发布时间】:2015-10-23 07:49:22
【问题描述】:
所以我正在构建一个相当简单的网站,允许用户创建和编辑个人资料。我正在为该网站创建 URL,这些 URL 遵循以下“规则”:
-
www.website.com应该重定向到主页。 -
www.website.com/profile/person应该重定向到person的个人资料。 -
www.website.com/profile/person/extra/useless/info应重定向到person的个人资料,因为 URL 应在profile/person/之后“修剪”。 -
www.website.com/profile应该重定向回www.website.com,这将重定向到主页。
到目前为止我的代码如下。
# my_site/urls.py
from django.conf.urls import include, url
from django.contrib import admin
urlpatterns = [
url(r'^$', include('my_app.urls')),
url(r'^profile/', include('my_app.urls')),
url(r'^admin/', include(admin.site.urls)),
]
第 2 部分:
# my_app/urls.py
from django.conf.urls import url
from django.http import HttpResponse
from . import views
urlpatterns = [
url(r'^(?P<username>[\w-]*)/$', views.profile, name='profile'),
url(r'^(?P<username>[^\w-])/$', views.profile, name='profile'), # still link to the profile
url(r'^$', views.home, name="home"),
]
使用此代码,当用户输入www.mysite.com/profile 时,用户被 重定向到主页,但地址栏仍然显示www.mysite.com/profile,这是我不想要的。我希望它阅读www.mysite.com。另外,我上面给出的规则列表中的第三条规则也没有被遵守。我正在考虑有一个 URL“清理”功能,它可以修剪 URL 中不需要的部分,但我不知道如何做到这一点。任何帮助将不胜感激。
非常感谢。
【问题讨论】:
-
“主页”和个人资料页一样吗?我问这个是因为您将所有应用程序的 url 指向views.profile。你也可以发布你的views.py吗?
-
我错了。我的意思是指向
views.home。我的错。