Closed V-FOR-VEND3TTA closed 1 month ago
Creating a custom 404 error page in Django involves defining a custom view to handle 404 errors, configuring the view in the settings, and creating a template for the 404 page.
First, create a 404.html
template that will be displayed when a 404 error occurs. Place this file in your templates directory.
<!-- templates/404.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Page Not Found</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
<style>
.container {
margin-top: 100px;
text-align: center;
}
</style>
</head>
<body>
<div class="container">
<h1>404 - Page Not Found</h1>
<p>Sorry, the page you are looking for does not exist.</p>
<a class="btn btn-primary" href="{% url 'dashboard' %}">Go to Dashboard</a>
<a class="btn btn-secondary" href="{% url 'login' %}">Login</a>
</div>
</body>
</html>
urls.py
In your main urls.py
, add a handler for the 404 error.
# urls.py (main project directory)
from django.conf.urls import handler404
from django.shortcuts import render
def custom_404(request, exception):
return render(request, '404.html', status=404)
handler404 = custom_404
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('returns_exchanges.urls')),
# Other URL patterns...
]
Ensure your settings are configured to use the custom error pages in debug mode. Set DEBUG
to False
and add your templates' directory to the TEMPLATES
setting.
# settings.py
DEBUG = False
ALLOWED_HOSTS = ['*']
Make sure your templates
directory is correctly structured and recognized by Django. Typically, this directory should be at the project root level or within an app directory.
Here is what we did to create a custom 404 error page:
404.html
file in the templates directory.urls.py
.settings.py
to use the custom error page when DEBUG
is False
.With these steps, your Django project will display a custom 404 error page whenever a user tries to access a URL that doesn't exist.
How do we handle incorrect URL insertions?