Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django tutorial: custom 404 and 500 views

Windows 7
Python 2.7.3
Django 1.5
python manage.py runserver

I am following the tutorial as available at 'https://docs.djangoproject.com/en/1.5/intro/tutorial03/'

I got as far as the 'Write a 404 (page not found) view' before things got wierd.

I have tried to work out how to make a custom 404 view. However, I am not sure:

A. Where exactly the custom 404.html file should reside. Should it be in my project directory tree or in my Django directory tree. My project directory tree looks like this,

1> mysite  
2>     - mysite  
3>     - polls  
4>         - templates  
5>             - polls  
6>     - templates  
7>         - admin  

Currently the 404.html is @ 6>

B. What modifications have to be made where? I understand that a handler404 and a handler500 need to be set in the 'root' url conf. I have a url.py residing @ 2> and 3> (see tree above). Assuming that 2> is the correct place I assume that the syntax is as follows,

handler404 = 'templates.404'
handler500 = 'templates.500'

What else needs to be set, where?

like image 688
SeeGull Avatar asked Mar 19 '13 10:03

SeeGull


1 Answers

As I can see you have a little mistake, but dont worry.

Look, try this:

handler404 = 'mysite.views.error404'

Then in mysite (the second mysite) creates a views.py if you dont have. In that views.py put:

from django.shortcuts import render

def error404(request):
    return render(request,'404.html')

and thats all! In templates, create that file and do something nice!

Remember that only works in production (DEBUG=False) otherwise django use the traceback. Is the same for 505, and you maybe can try handler404 = 'polls.views.see404' and put in the views.py then but you know, tastes are different hehehe.

Now, try something else, for example: comment in the urls.py

#handler404 = 'mysite.views.error404'

and remove too in the views.py the def.

In the index of your templates file creates a simple 404.html. Run the server in production and produce that 404 error, what happened?

like image 167
Shopper Avatar answered Oct 16 '22 11:10

Shopper