Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 774
Milano Avatar asked Sep 06 '25 03:09

Milano


1 Answers

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

like image 85
Daniel Williams Avatar answered Sep 07 '25 21:09

Daniel Williams