gamer
gamer

Reputation: 5863

django redirecting blank url to named url

I have my url:

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

When I enter localhost:8000/home I get my homepage but what I want is when I just enter I get my homepage. I mean I want to redirect to the above homepage url when user enters only my site likewww.xyz.com not www.xyz.com/home

I dont want to configure in this way

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

Thanx in advance

Upvotes: 5

Views: 3814

Answers (2)

sh_mykola
sh_mykola

Reputation: 61

I found this solution (long story short, you need to add views.py to your main project folder and make view which redirect your empty route to your url):

  1. In your urls.py inside urlpatterns add this:

    urlpatterns = [
    ...
    path("", views.home, name="home"),
    ...
    ]
    
  2. In main Django folder create views.py and import it in urls.py example

  3. In views.py add this code:

    from django.shortcuts import render, redirect
    
    def home(request):
        return redirect("blog:index") # redirect to your page
    
  4. Now every time your url will be empty like (localhost:8000) it will be redirected to (localhost:8000/your_adress). Also, you can use this not only with blank url, but anywhere you need this sort of redirection

Upvotes: 5

catavaran
catavaran

Reputation: 45575

Use generic RedirectView:

from django.views.generic.base import RedirectView

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

Upvotes: 9

Related Questions