Milano
Milano

Reputation: 18745

How to redirect (including URL change) in Django?

I have created an index.html. I want this page (or the view) to be shown when somebody goes to http://www.mypage.com/ and http://www.mypage.com/index/. Since I'm new to Django, this could be a bad way: In my URLS.PY:

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^$',views.index),
    url(r'^index/$',views.index),...
    ...

This works properly but I'm curious, whether is it possible to change the url from http://www.mypage.com/ to http://www.mypage.com/index/ when somebody goes to http://www.mypage.com/.

I've already tried change this:

url(r'^$',views.index),

to this:

url(r'^$','/index/'),

but it raises error:

Could not import '/index/'. The path must be fully qualified.

Could somebody give me an advice how to do that?

Upvotes: 4

Views: 15718

Answers (2)

Daniel Williams
Daniel Williams

Reputation: 692

If you want to do it via code it is:

from django.http import HttpResponseRedirect

def frontpage(request):
    ...
    return HttpResponseRedirect('/index/')

But you can also do it directly in the urls rules:

from django.views.generic import RedirectView

urlpatterns = patterns('',
    (r'^$', RedirectView.as_view(url='/index/')),
)

For reference, see this post: https://stackoverflow.com/a/523366/5770129

Upvotes: 13

Remi Smirra
Remi Smirra

Reputation: 2539

What you could do, is the following. Put this in your urls.py:

url(r'^$',views.redirect_index),

and in your views:

def redirect_index(request):
    return redirect('index')

Upvotes: 3

Related Questions