avatarGörkem Arslan

Free AI web copilot to create summaries, insights and extended knowledge, download it at here

3236

Abstract

ion, you need to change <code>ALLOWED_HOSTS</code> to <code>'mydomain.com'</code> .</p><p id="3fbd">Refresh the page.</p><figure id="869a"><img src="https://cdn-images-1.readmedium.com/v2/resize:fit:800/1*yUSupCJp0G735f6QS53VYQ.png"><figcaption>Django Not Found Page after DEBUG = True (Image by author)</figcaption></figure><p id="1552">This is the page we are going to customize with our template.</p><p id="9fcf">Use this command and create a file under the <code>mysite</code> folder.</p><div id="ad48"><pre><span class="hljs-meta prompt_">$ </span><span class="language-bash"><span class="hljs-built_in">touch</span> mysite/views.py</span></pre></div><p id="62e9">I know it is weird to have a <code>views.py</code> file under the project directory. We are always told that <code>views.py</code> is a file that is under each app directory, not the project itself. But this is the suggested way in the <a href="https://docs.djangoproject.com/en/3.2/topics/http/views/#customizing-error-views">official document</a>.</p><p id="1592">Your Django project should look like this:</p><div id="571a"><pre>. ├── db<span class="hljs-selector-class">.sqlite3</span> ├── manage<span class="hljs-selector-class">.py</span> └── mysite ├── init<span class="hljs-selector-class">.py</span> ├── pycache ├── asgi<span class="hljs-selector-class">.py</span> ├── settings<span class="hljs-selector-class">.py</span> ├── urls<span class="hljs-selector-class">.py</span> ├── views<span class="hljs-selector-class">.py</span> └── wsgi.py</pre></div><p id="675c">Now we will add a function that handles 404 error by putting these lines to the <code>mysite/views.py</code> file:</p><div id="574a"><pre><span class="hljs-keyword">from</span> django.shortcuts <span class="hljs-keyword">import</span> render</pre></div><div id="5813"><pre><span class="hljs-keyword">def</span> <span class="hljs-title function_">page_not_found_view</span>(<span class="hljs-params">request, exception</span>): <span class="hljs-keyword">return</span> render(request, <span class="hljs-string">'404.html'</span>, status=<span class="hljs-number">404</span>)</pre></div><p id="1b72">Don’t forget to add this function to the bottom of <code>mysite/urls.py</code> file:</p><div id="425d"><pre><span class="hljs-attribute">handler404</span> <span class="hljs-operator">=</span> <span class="hljs-string">"mysite.views.page_not_found_view"</span></pre></div><p id="5dcf">In the end, <code>mysite/urls.py</code>file becomes:</p><div id="ad97"><pre><span class="hljs-keyword">from</span> django.contrib <span class="hljs-keyword">import</span> <span class="hljs-keyword">admin</span> <span class="hljs-keyword">from</span> django.urls <span class="hljs-keyword">import</span> <span class="hljs-type">path</span></pre></div><div id="2fb7"><pre><span class="hljs-attr">urlpatterns</span> = [ path(<span class="hljs-string">'admin/'</span>, admin.site.urls), ]</pre></div><div id="7314"><pre><span class="hljs-attribute">handler404</span> <span class="hljs-operator">=</span> <span class="hljs-string">"django_404_project.views.page_not_found_view"</span></pre></div><p id="b28e">First, we need to create a <code>templates</code> folder and th

Options

en we will add a <code>404.html</code> file to this folder.</p><div id="c39b"><pre><span class="hljs-meta prompt_"> </span><span class="language-bash"><span class="hljs-built_in">mkdir</span> templates</span> <span class="hljs-meta prompt_"> </span><span class="language-bash"><span class="hljs-built_in">touch</span> templates/404.html</span></pre></div><p id="a16d">You need to tell Django where your <code>templates</code> folder is located so update the <code>settings.py</code> file.</p><div id="fb0b"><pre><span class="hljs-keyword">import</span> os</pre></div><div id="0ef0"><pre><span class="hljs-attr">TEMPLATES</span> = [ { ... <span class="hljs-string">'DIRS'</span>: [os.path.join(BASE_DIR, <span class="hljs-string">'templates'</span>)], ... }, ]</pre></div><p id="95e3">In <code>404.html</code> you are now able to customize the error message page as you desire. I am keeping it simple:</p><div id="6e1e"><pre><span class="hljs-tag"><<span class="hljs-name">h1</span>></span>404 Page Not Found<span class="hljs-tag"></<span class="hljs-name">h1</span>></span> <span class="hljs-tag"><<span class="hljs-name">p</span>></span>My Custom 404 Page Not Found!<span class="hljs-tag"></<span class="hljs-name">p</span>></span></pre></div><p id="2e8f">Before refreshing the page, be sure that your project structure should be like this:</p><div id="425a"><pre>. ├── db<span class="hljs-selector-class">.sqlite3</span> ├── manage<span class="hljs-selector-class">.py</span> ├── mysite │ ├── init<span class="hljs-selector-class">.py</span> │ ├── pycache │ ├── asgi<span class="hljs-selector-class">.py</span> │ ├── settings<span class="hljs-selector-class">.py</span> │ ├── urls<span class="hljs-selector-class">.py</span> │ ├── views<span class="hljs-selector-class">.py</span> │ └── wsgi<span class="hljs-selector-class">.py</span> └── templates └── <span class="hljs-number">404</span>.html</pre></div><p id="73fa">Now you can go to any page that does not exist on your website. The <code>404.html</code> template will handle all of them.</p><figure id="81c2"><img src="https://cdn-images-1.readmedium.com/v2/resize:fit:800/1*3BQ7g23oEvfSHkodQpg6Og.png"><figcaption>Customized 404 Not Found Page (Image by author)</figcaption></figure><p id="f54a">Voila! Our custom 404 Page Not Found is visible for any non-existing page on your website.</p><p id="28df">Thank you for reading my article. I hope you enjoy it!</p><p id="da23">You might also be interested in:</p><div id="3975" class="link-block"> <a href="https://python.plainenglish.io/9-python-tricks-to-become-a-better-data-scientist-eb26970b4160"> <div> <div> <h2>9 Python Tricks to Become a Better Data Scientist</h2> <div><h3>You should know these awesome tricks to have a better data scientist career</h3></div> <div><p>python.plainenglish.io</p></div> </div> <div> <div style="background-image: url(https://miro.readmedium.com/v2/resize:fit:320/0*xGKGn63LzUlZIuQ9)"></div> </div> </div> </a> </div></article></body>

Django: Customize 404 Error Page

Customizing 404 Error Page is one of the best practices in Django projects. Let’s learn how to handle 404 errors with our custom 404 Not Found page.

Photo by Erik Mclean on Unsplash

404 Page Not Found should be the most famous status code. In production, a good Django project has to handle this error with your own customized page. I will show you how to accomplish this with simple steps.

Let’s create a Django project without losing time.

Open your console and write these lines:

$ cd Desktop
$ mkdir mysite
$ cd mysite

Then create a Django project:

$ django-admin startproject mysite .

We will execute this line to run the server:

$ python manage.py runserver

If you visit http://127.0.0.1:8000/ you will see the Django welcome page.

Django Welcome Page (Image by author)

Let’s try to go to a non-existing page on our website. For example, I will go to http://127.0.0.1:8000/page.

Default Django Not Found Page (Image by author)

At the bottom of the page, the message says:

You’re seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page.

Let’s do that by turning off Django debug mode. For this, we need to update the settings.py file.

DEBUG = False
ALLOWED_HOSTS = ['127.0.0.1']

Note: In production, you need to change ALLOWED_HOSTS to 'mydomain.com' .

Refresh the page.

Django Not Found Page after DEBUG = True (Image by author)

This is the page we are going to customize with our template.

Use this command and create a file under the mysite folder.

$ touch mysite/views.py

I know it is weird to have a views.py file under the project directory. We are always told that views.py is a file that is under each app directory, not the project itself. But this is the suggested way in the official document.

Your Django project should look like this:

.
├── db.sqlite3
├── manage.py
└── mysite
    ├── __init__.py
    ├── __pycache__
    ├── asgi.py
    ├── settings.py
    ├── urls.py
    ├── views.py
    └── wsgi.py

Now we will add a function that handles 404 error by putting these lines to the mysite/views.py file:

from django.shortcuts import render
def page_not_found_view(request, exception):
    return render(request, '404.html', status=404)

Don’t forget to add this function to the bottom of mysite/urls.py file:

handler404 = "mysite.views.page_not_found_view"

In the end, mysite/urls.pyfile becomes:

from django.contrib import admin
from django.urls import path
urlpatterns = [
    path('admin/', admin.site.urls),
]
handler404 = "django_404_project.views.page_not_found_view"

First, we need to create a templates folder and then we will add a 404.html file to this folder.

$ mkdir templates
$ touch templates/404.html

You need to tell Django where your templates folder is located so update the settings.py file.

import os
TEMPLATES = [
    {
        ...
        'DIRS': [os.path.join(BASE_DIR, 'templates')],
        ...
    },
]

In 404.html you are now able to customize the error message page as you desire. I am keeping it simple:

<h1>404 Page Not Found</h1>
<p>My Custom 404 Page Not Found!</p>

Before refreshing the page, be sure that your project structure should be like this:

.
├── db.sqlite3
├── manage.py
├── mysite
│   ├── __init__.py
│   ├── __pycache__
│   ├── asgi.py
│   ├── settings.py
│   ├── urls.py
│   ├── views.py
│   └── wsgi.py
└── templates
    └── 404.html

Now you can go to any page that does not exist on your website. The 404.html template will handle all of them.

Customized 404 Not Found Page (Image by author)

Voila! Our custom 404 Page Not Found is visible for any non-existing page on your website.

Thank you for reading my article. I hope you enjoy it!

You might also be interested in:

Python
Django
Software Development
Data Science
Web Development
Recommended from ReadMedium