【问题标题】:django redirecting blank url to named urldjango 将空白 url 重定向到命名 url
【发布时间】:2015-03-09 06:43:26
【问题描述】:

我有我的网址:

url(r'^home/', HomeQuestionView, name='home_question') ,

当我输入localhost:8000/home 时,我得到了我的主页,但我想要的是当我刚刚输入时,我得到了我的主页。 我的意思是当用户只输入我的网站时,我想重定向到上面的主页网址,例如www.xyz.com 而不是www.xyz.com/home

我不想这样配置

url(r'^', HomeQuestionView, name='home_question') ,

提前感谢

【问题讨论】:

  • 您不想使用 r'^' 配置的任何特殊原因?
  • 您不想让您的网站按照您想要的方式运行吗?

标签: python django url


【解决方案1】:

使用通用RedirectView:

from django.views.generic.base import RedirectView

url(r'^$', RedirectView.as_view(url='/home/')),

【讨论】:

    【解决方案2】:

    我找到了这个解决方案(长话短说,您需要将views.py 添加到您的主项目文件夹并制作将您的空路由重定向到您的url 的视图):

    1. 在你的 urls.py 里面的 urlpatterns 添加这个:

      urlpatterns = [
      ...
      path("", views.home, name="home"),
      ...
      ]
      
    2. 在主 Django 文件夹中创建 views.py 并将其导入 urls.py example

    3. 在views.py中添加这段代码:

      from django.shortcuts import render, redirect
      
      def home(request):
          return redirect("blog:index") # redirect to your page
      
    4. 现在每次你的 url 都会像 (localhost:8000) 这样为空时,它会被重定向到 (localhost:8000/your_adress)。此外,您不仅可以使用空白 url,还可以在任何需要这种重定向的地方使用它

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-07-14
      • 1970-01-01
      • 1970-01-01
      • 2021-10-20
      • 2019-02-01
      • 2015-03-18
      • 2011-08-06
      • 2019-05-14
      相关资源
      最近更新 更多