404 view -> redirect to index

1,674 views
Skip to first unread message

galago

unread,
Jan 18, 2011, 7:22:13 AM1/18/11
to django...@googlegroups.com
I try to redirect from 404 view to my index page. In url.py i added: 
handler404 = 'index.views.custom404'

in my index i have:
def custom404(request):    
    return HttpResponseRedirect(reverse('index'))

But it doesn't work.
Should I do something more?

Ivo Brodien

unread,
Jan 18, 2011, 7:30:39 AM1/18/11
to django...@googlegroups.com, galago
Are you sure, that you have a url pattern called ‘’view? in reverse you have to pass the name of the rule, not the views method name.

> --
> You received this message because you are subscribed to the Google Groups "Django users" group.
> To post to this group, send email to django...@googlegroups.com.
> To unsubscribe from this group, send email to django-users...@googlegroups.com.
> For more options, visit this group at http://groups.google.com/group/django-users?hl=en.

galago

unread,
Jan 18, 2011, 7:35:32 AM1/18/11
to django...@googlegroups.com, galago
Yes I have a index pattern:
urlpatterns = patterns('',
    url(r'^$', 'index.views.index', name='index'),.......

When I add print to my method:
def custom404(request):
    print 'foo'
    return HttpResponseRedirect(reverse('index'))

It prints out but it doesn't redirect me to index. Instead it displays my 404.html page.

Ivo Brodien

unread,
Jan 18, 2011, 7:42:01 AM1/18/11
to django...@googlegroups.com, galago
I guess that django catches the 404 Error Code somehow somewhere else than in the handler? Maybe you have to set the HTTP Code to 200?


Thomas

unread,
Jan 18, 2011, 8:04:17 AM1/18/11
to django...@googlegroups.com, galago

why just not copy the 'templates/index.html' template to 'templates/404.html' - ready

*not*sure*about*the*correctness*of*this*

Thomas

unread,
Jan 18, 2011, 8:10:44 AM1/18/11
to django...@googlegroups.com, galago

The book "The definitive Guide to Django" says on page 476:

---8<---

... if you want to override the 404 view, you can specify 'handler404' in your URLconf, like so:


from django.conf.urls.defaults import *

urlpatterns = patterns ('',
...
)

handler404 = 'mysite.views.my_custom_404_view'

Behind the scenes ...

---8<---


hope this helps,

good luck,
TR

Am 18.01.2011 um 13:42 schrieb Ivo Brodien:

natebeacham

unread,
Jan 18, 2011, 12:59:48 PM1/18/11
to Django users
Thomas: That is what he has.

Make sure you turn DEBUG off. Your custom 404 handler will only be
used when you are not in debug mode.

Cheers
> >> For more options, visit this group athttp://groups.google.com/group/django-users?hl=en.
Reply all
Reply to author
Forward
0 new messages