Handling 404’s (pages not found) in Django web application framework is easy and quite systematic. You can customize how Django should behave when a certain URL doesn’t exist (i.e., when a view function doesn’t return an HTTP response).
By default, Django runs with DEBUG = True in settings.py, which tells Django to serve the detailed error page whenever 404 error occurs. However, when your Django application is in production, you should turn DEBUG off, making Django to serve the simple 404 error page.
Here is a natural way how to manage 404 errors:
First, update your settings.py file. Change DEBUG to False and add your host to ALLOWED\_HOSTS. Here is an example:
```
DEBUG = False
ALLOWED_HOSTS = [‘your_hostname’]
```
Remember to replace ‘your\_hostname’ with the hostname you’re using. If it’s a local development server, use ‘localhost’ or ’127.0.0.1’.
Django provides a view function, django.views.defaults.page_not_found, to handle 404 errors. Django raises a Http404 exception, then this view function is called to prepare the 404 response. You can customize it by your own view function. Here is an example:
```
from django.shortcuts import render
from django.http import Http404
def my_custom_page_not_found_view(request, exception):
data = {“name”: “ThePythonDjango.com”}
return render(request,‘my_404_view.html’, data)
```
Add your custom function to the handler404 in your root URLConf. In your\_project/urls.py file:
```
handler404 = ‘your_app.views.my_custom_page_not_found_view‘
```
To customize the template for 404 error page, prepare my_404_view.html file in your project’s top-level templates directory.
Ensure your TEMPLATE\_DIRS in settings.py includes the path of this directory.
Note: When DEBUG is True, Django would serve detailed page-not-found page and that would skip your custom 404 error page. So, you can temporarily set DEBUG = False to test your custom 404 error page.
Sources:
- Django Project: How to customize error views – https://docs.djangoproject.com/en/3.2/topics/http/views/#customizing-error-views
- The University of Arizona Libraries: Using Django – https://new.library.arizona.edu/support/developers/django
- Web Programming with Python and JavaScript: Django – https://cs50.harvard.edu/web/2020/notes/4/
- Mozilla Developer Network: Django Tutorial – MDN Web Docs – https://developer.mozilla.org/en-US/docs/Learn/Server-side/Django