The Wayback Machine - https://web.archive.org/web/20240629004112/https://www.geeksforgeeks.org/django-creating-a-404-error-page/
Open In App

Django – Creating a 404 Error Page

Last Updated : 28 Mar, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

The 404 error is raised when the URL called upon doesn’t exist or has not been defined yet. This is commonly referred to as Page does not exist error. To handle requests from the undefined URLs in a website an error page is created. If these types of URLs are requested by the user then this error page gets executed to reflect the user that the page doesn’t exist and you can further redirect them to another URL like the Homepage. Using this technique we can also improve the SEO of our website.

In this article, we will create a simple 404 error page for our application.

Implementation:

Step 1 :  Go to settings.py file of your application and change this

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = False

ALLOWED_HOSTS = ['*']

Step 2:  Go to the urls.py file of your application and put the below code:

Python3




from django.contrib import admin
from django.urls import include, path
 
# add the following path in the
# url patterns
urlpatterns = [
    path('', include('pages.urls'))
]
 
# add a flag for
# handling the 404 error
handler404 = 'pages.views.error_404_view'


Step 3: After that go to open up the views.py  of your app and add the below code: 

Python3




from django.conf import settings
from django.shortcuts import redirect
 
 
def error_404_view(request, exception):
   
    # we add the path to the 404.html file
    # here. The name of our HTML file is 404.html
    return render(request, '404.html')


Step 4: Now just need to add the HTML page to your template page and your work is finished.

HTML




{% load static %}
<!DOCTYPE html>
<!--[if IE 8 ]>
<html class="no-js oldie ie8" lang="en">
   <![endif]-->
   <!--[if IE 9 ]>
   <html class="no-js oldie ie9" lang="en">
      <![endif]-->
      <!--[if (gte IE 9)|!(IE)]><!-->
      <html class="no-js" lang="en">
         <!--<![endif]-->
         <head>
            <!--- basic page needs
               ================================================== -->
            <meta charset="utf-8">
            <title>Web Developer</title>
            <link href="{% static 'img/Demo/favicon.png' %}" rel="shortcut icon"/>
            <meta charset="UTF-8" />
            <meta http-equiv="X-UA-Compatible" content="IE=edge">
            <meta name="description" content="Alphaandroid - Creative Agency of web developers">
            <meta name="author" content="Pavan And Romil">
            <meta name="keywords" content="Web developer (using coding), Digital Marketing" />
            <!-- mobile specific metas
               ================================================== -->
            <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
            <!-- CSS
               ================================================== -->
            <link rel="stylesheet" href="{% static 'css/error404/base.css' %}">
            <link rel="stylesheet" href="{% static 'css/error404/main.css' %}">
            <link rel="stylesheet" href="{% static 'css/error404/vendor.css' %}">
            <!-- script
               ================================================== -->
            <script src="{% static 'js/error404/modernizr.js' %}"></script>
            <!-- favicons
               ================================================== -->
            <link rel="icon" type="image/png" href="{% static 'favicon.png' %}">
            <!-- Google Tag Manager -->
            <script>(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':
               new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
               j=d.createElement(s),dl=l!='dataLayer'?'&l;='+l:'';j.async=true;j.src=
               'https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);
               })(window,document,'script','dataLayer','GTM-MRJ5QRJ');
            </script>
            <!-- End Google Tag Manager -->
         </head>
         <body>
            <!-- Google Tag Manager (noscript) -->
            <noscript><iframe src="https://www.googletagmanager.com/ns.html?id=GTM-MRJ5QRJ"
               height="0" width="0" style="display:none;visibility:hidden"></iframe></noscript>
            <!-- End Google Tag Manager (noscript) -->
            <!-- header
               ================================================== -->
            {% comment %}
            <header class="main-header">
               <div class="row">
                  <div class="logo">
                     <a href="index.html">Alpha Android</a>
                  </div>
               </div>
               <a class="menu-toggle" href="#"><span>Menu</span></a>   
            </header>
            <!-- /header --> {% endcomment %}
            <!-- navigation
               ================================================== -->
            {% comment %}
            <nav id="menu-nav-wrap">
               <h5>Site Pages</h5>
               <ul class="nav-list">
                  <li><a href="/" title="">Home</a></li>
                  <li><a href="#" title="">About</a></li>
                  <li><a href="#" title="">Contact</a></li>
               </ul>
               <h5>Some Text</h5>
                
 
 
 
<p>Lorem ipsum Non non Duis adipisicing pariatur eu enim Ut in aliqua dolor esse sed est in sit exercitation eiusmod aliquip consequat.</p>
 
 
 
 
            </nav>
            {% endcomment %}
            <!-- main content
               ================================================== -->
            <main id="main-404-content" class="main-content-particle-js">
               <div class="content-wrap">
                  <div class="shadow-overlay"></div>
                  <div class="main-content">
                     <div class="row">
                        <div class="col-twelve">
                           <h1 class="kern-this">404 Error.</h1>
                            
 
 
 
<p>
                              Oooooops! Looks like nothing was found at this location.
                              Maybe try one of the links below, click on the top menu
                              or try a search?
                           </p>
 
 
 
 
                           {% comment %}
                           <div class="search">
                              <form>
                                 <input type="text" id="s" name="s" class="search-field" placeholder="Type and hit enter â€Ķ">
                              </form>
                           </div>
                           {% endcomment %}
                        </div>
                        <!-- /twelve -->                       
                     </div>
                     <!-- /row -->                    
                  </div>
                  <!-- /main-content -->
                  <footer>
                     <div class="row">
                        <div class="col-seven tab-full social-links pull-right">
                           <ul>
                              <li><a href="#"><i class="fa fa-facebook"></i></a></li>
                              <li><a href="#"><i class="fa fa-behance"></i></a></li>
                              <li><a href="#"><i class="fa fa-twitter"></i></a></li>
                              <li><a href="#"><i class="fa fa-dribbble"></i></a></li>
                              <li><a href="#"><i class="fa fa-instagram"></i></a></li>
                           </ul>
                        </div>
                        <div class="col-five tab-full bottom-links">
                           <ul class="links">
                              <li><a href="/">Homepage</a></li>
                              <li><a href="/about-us/">About Us</a></li>
                              {% comment %}
                              <li><a href="/contact-us/">Contact Us</a></li>
                              {% endcomment %}
                              <li><a href="mailto:Contact@alphaandroid.com">Report Error</a></li>
                           </ul>
                           <div class="credits">
                               
 
 
 
<p>Design by <a href="http://www.alphaandroid.com/" title="styleshout">alphaandroid.com</a></p>
 
 
 
 
                           </div>
                        </div>
                     </div>
                     <!-- /row -->                     
                  </footer>
               </div>
               <!-- /content-wrap -->
            </main>
            <!-- /main-404-content -->
            <div id="preloader">
               <div id="loader"></div>
            </div>
            <!-- Java Script
               ================================================== -->
            <script src="{% static 'js/error404/jquery-2.1.3.min.js' %}"></script>
            <script src="{% static 'js/error404/plugins.js' %}"></script>
            <script src="{% static 'js/error404/main.js' %}"></script>
         </body>
      </html>


Step 5: Lastly whenever the 404 error is raised it will show them the 404.html file.:

Output:

Note: You will be able to see the output of this page only and only when you have made that website live on hosting or when you will set debug mode “False” and set your allowed host.



Similar Reads

Handling 404 Error in Flask
Prerequisite: Creating simple application in Flask A 404 Error is showed whenever a page is not found. Maybe the owner changed its URL and forgot to change the link or maybe they deleted the page itself. Every site needs a Custom Error page to avoid the user to see the default Ugly Error page. GeeksforGeeks also has a customized error page. If we t
4 min read
Django - Creating a Multi-Page Website
Django is a python based open-source framework used for web development. Django allows the usage of the M-T-V (Model-Templates-View) architectural pattern for the creation and deployment of a functional website. This article aims at creating a multipage personal profile website using Django to explain all the main concepts and aspects of the Django
8 min read
Python Django Handling Custom Error Page
To handle error reporting in Django, you can utilize Django's built-in form validation mechanisms and Django's error handling capabilities. In this article, I'll demonstrate how to implement error handling. If there are errors in the form submission, the user will be notified of the errors. Required Modules Install DjangoCreate Virtual Env Python D
4 min read
Django Introduction | Set 2 (Creating a Project)
Note- This article is in continuation of Django introduction. Popularity of Django Django is used in many popular sites like as: Disqus, Instagram, Knight Foundation, MacArthur Foundation, Mozilla, National Geographic etc. There are more than 5k online sites based on Django framework. ( Source ) Sites like Hot Frameworks assess the popularity of a
3 min read
Django - Creating Apps | Set - 1
Prerequisites: Django – Dealing with warnings Why do we need apps? In Django Set 2 (Creating a Project), we saw how we can display text in our browser using Django but that is not the best and pythonic way. Django recommends using the project-app relationship to build Django projects. Any website contains different sections. For example, Geeksforge
1 min read
Django - Creating apps | Set - 2
In the previous article, we discussed why apps are important in Django project management? What are the benefits of using Django apps? In this article, we will discuss what are we going to build and how do apps play a vital role in Django projects? Project outline - We will build a localhost e-commerce mobile phone website which can show us details
2 min read
Creating and Using Serializers - Django REST Framework
In Django REST Framework the very concept of Serializing is to convert DB data to a datatype that can be used by javascript. Serializers allow complex data such as querysets and model instances to be converted to native Python datatypes that can then be easily rendered into JSON, XML or other content types. Serializers also provide deserialization,
3 min read
Creating custom user model API extending AbstractUser in Django
Every new Django project should use a custom user model. The official Django documentation says it is “highly recommended” but I’ll go a step further and say without hesitation: You are straight up crazy not to use a custom user model up front. Why do u need a custom user model in Django? When you start your project with a custom user model, stop t
4 min read
Django project - Creating a Basic E-commerce Website for Displaying Products
Project Title - Basic Ecommerce Website using Django Django is a powerful framework based on python. Here we will see how to create a basic e-commerce website in Django. This project includes storing products in the database and show them on the website. Refer to the following articles to check how to create a project and an app in Django. How to C
3 min read
Creating multiple user types and using proxy models in Python Django
In this article, we will understand the concept of the proxy model and the implementation of multiple user types depending on the requirements of your application in Django. What is the Proxy model in Django? An inherited proxy model can have a few extra functionalities, methods, and different behaviors than the parent model as defined by the creat
9 min read
three90RightbarBannerImg