【问题标题】:URL routing in the Django frameworkDjango 框架中的 URL 路由
【发布时间】: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。我的错。

标签: django http redirect web


【解决方案1】:

要在浏览器中更改路径,您需要使用实际的 http 重定向,而不仅仅是 Django url 匹配中的后备。

# 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'^admin/', include(admin.site.urls)),
]


# my_app/urls.py

from django.conf.urls import url
from django.views.generic import RedirectView    

from . import views

urlpatterns = [
   url(r'^profile/(?P<username>[^/]+)/$', views.profile, name='profile'),
   url(r'^profile/(?P<username>[^/]+)/(.*)?', RedirectView.as_view(pattern_name='profile')),
   url(r'^profile/$', RedirectView.as_view(pattern_name='home')),
   url(r'^$', views.profile, name="home"),
]

解释一下:

  • ^profile/(?P&lt;username&gt;[^/]+)/$ 匹配 mysite.com/profile/my-user-name/,末尾没有垃圾
  • '^profile/(?P&lt;username&gt;[^/]+)/(.*)?' 匹配末尾带有垃圾的大小写(在有效用户名和 / 之后)...您希望在查找垃圾部分之前需要斜杠,否则如果您有两个用户 johnjohnsmith,您会始终将 url 中的 johnsmith 匹配为 john 用户(将 smith 视为额外的垃圾)。然后我们做一个真正的 http 重定向到规范的配置文件 url
  • '^profile/$' 仅匹配 mysite.com/profile/ 并执行真正的 http 重定向到主页

有关重定向的更多信息,请参阅:https://stackoverflow.com/a/15706497/202168

当然还有文档:
https://docs.djangoproject.com/en/1.8/ref/class-based-views/base/#redirectview
https://docs.djangoproject.com/en/1.8/topics/http/shortcuts/#redirect

【讨论】:

    猜你喜欢
    • 2020-01-27
    • 2016-01-29
    • 2011-04-20
    • 1970-01-01
    • 2011-02-05
    • 1970-01-01
    • 1970-01-01
    • 2013-09-20
    • 2015-02-05
    相关资源
    最近更新 更多