3

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?

Milano
  • 18,048
  • 37
  • 153
  • 353

2 Answers2

13

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

Community
  • 1
  • 1
Daniel Williams
  • 672
  • 5
  • 8
  • If you are using Django < 1.9, you probably want `RedirectView.as_view(url='/index/', permanent=False)`, because it defaults to a permanent redirect until Django 1.9. – Alasdair Jan 11 '16 at 14:05
  • 2
    It would be slightly better to use `pattern_name='index'`, rather than `url='/index/'`, to avoid hardcoding the url. – Alasdair Jan 11 '16 at 14:06
3

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')
Remi Smirra
  • 2,499
  • 1
  • 14
  • 15
  • Which is the RightWay to solve the problem - you don't want to have two distinct urls serving the same content (unless you don't care about SEO that is). – bruno desthuilliers Jan 11 '16 at 13:34