django 将空白 url 重定向到命名 url

django redirecting blank url to named url

我有我的 url:

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

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

我想重定向到上面的主页 url

我不想这样配置

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

提前致谢

使用通用 RedirectView:

from django.views.generic.base import RedirectView

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

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

  1. 在你的 urls.py 里面 url 模式添加这个:

    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,还可以在任何需要这种重定向的地方使用