Displaying custom 404 error (page not found) page in Django 2.0

It happens very frequently that a visitor on your website typed a wrong URL or the page user is looking for no longer exists.

What do you do to handle such cases?

You have three options.

  • Redirect the visitor to home page, silently.
  • Show a boring 404 error page and then ask them to click on a link to go to home page.
  • Create your own funny/awesome/informative custom 404 error page.
In this article we will discuss the third option i.e. How to show your own error page in Django 2.0 project when a URL is not found.

Code is available on Github.


How to create your own custom 404 error page in Django:

A custom 404 error page can serve multiple other purposes apart from just telling the user that the link you visited is not correct.

You can ask user to subscribe or sign-up. Or you may show some funny stuff. 


django 404 not found

  

Steps to show custom 404 error page in Django:


Project Setup:
Create a virtual environment using python3 and activate it.

- Once virtual environment is activated, install the Django 2.0 in it using pip.

pip install Django==2.0.3


- Now go to the directory where you want to create project. - Run the below command to create a new project.

django-admin startproject error_404


- This will create a new folder error_404  in your current working directory. Inside project directory there will be manage.py  file.

- Now we will use manage.py  file to run django commands.

- Create a new app inside project. Use the below command to create new app.

python manage.py startapp myapp


- This will add a new app in your project. Tree structure of your project at this point will look like as below:

(django2) rana@Nitro:error_404$ tree
.
??? error_404
?   ??? __init__.py
?   ??? settings.py
?   ??? urls.py
?   ??? wsgi.py
??? manage.py
??? myapp
    ??? admin.py
    ??? apps.py
    ??? __init__.py
    ??? migrations
    ?   ??? __init__.py
    ??? models.py
    ??? tests.py
    ??? views.py

4 directories, 14 files


- Don't forget to add your newly created app to the list of installed apps in project settings.py  file.


error_404/settings.py:

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'myapp',
]
 

- Right now if you start your python server using command python manage.py runserver , you will see below output in your terminal.

(django2) rana@Nitro:error_404$ python manage.py runserver
Performing system checks...

System check identified no issues (0 silenced).

You have 14 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions.
Run 'python manage.py migrate' to apply them.

March 19, 2018 - 17:21:19
Django version 2.0.3, using settings 'error_404.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.


- And you can see your project is working just fine by going to localhost:8000 in your browser. If you seen below screen means all is good. 


django 404 not found


Showing 404 error page:

- If you try to go to some URL which doesn't exists yet like localhost:8000/abc, then it will show the default 404 page not found error page of Django. 


custom 404 error page in django


- When you will deploy the code on server, you will set DEBUG = False  and ALLOWED_HOST = ["your_domain"]  hence your incorrect URL will return response as shown below.


django 404 when debug is false


On your localhost you need to edit your project/settings.py file to show this error.


error_404/settings.py:

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

ALLOWED_HOSTS = ["*"]


Setting "*" in allowed hosts will let you run your project with any host when debug is false. Don't do this in production.

Now go inside your app and create urls.py file.


myapp/urls.py:

from django.urls import path

from . import views

urlpatterns = [
    path('', views.index, name='index'),
]
 


Custom 404 error page:

Now create a new view inside your views.py file. Mind the second parameter exception  in error view.


myapp/views.py:

from django.shortcuts import render
from django.http import HttpResponse


def error_404_view(request, exception):
    data = {"name": "ThePythonDjango.com"}
    return render(request,'myapp/error_404.html', data)


def index(request):
    return HttpResponse("Hello, world. You're at the Home page of Django sample project error 404.")


Create an HTML file which will show appropriate message or form or funny stuff in myapp/templates/myapp directory.


error_404.html:

<html>
  <head>
  </head>
  <body>
    <h1> This is a custom 404 error page which will 
         be shown instead of default 404 error page of Django everytime
         incorrect urls is entered in browser.
    </h1>
  </body>
</html>


Now go to urls.py  file of your project and update it. file error_404/urls.py will look like as below:

from django.contrib import admin
from django.urls import path, include
from django.conf.urls import handler404

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('myapp.urls')),
]
 
handler404 = 'myapp.views.error_404_view'


Now if you go to your browser and open any non-existent URL, you will be shown custom 404 error page.


Screenshot from

We need to set DEBUG = False and ALLOWED_HOST = ["*"] or whatever your host is in order to see custom 404 error page.


Code:

Code is available on Github. Please go through README file to setup the project on your machine.  

References:

  1. https://docs.djangoproject.com/en/2.0/ref/views/#error-views


Featured Image Source:  https://www.pinterest.com/pin/101612535313085400/   


Comment in case of any query.


Related Articles:
Python Script 3: Validate, format and Beautify JSON string Using Python
Validating json using python code, format and beautify json file using python, validate json file using python, how to validate, format and beautify json...
Encryption-Decryption in Python Django
How to encrypt and decrypt the content in DJango. Encrypting the critical information in Django App. Encrypting username, email and password in Django...
Adding Robots.txt file to Django Application
Adding robots.txt file in your Django application. Easiest way to add robots.txt file. Django application robots.txt file. Why should you add robots.txt file in your Django Application....
How to upgrade to paid account on PythonAnyWhere
Which is the best server for hosting Django Apps. Best hosting provider for Django Apps. Cheapest Django Hosting. PythonAnyWhere Reviews. Django Hosting....

0 thoughts on 'Displaying Custom 404 Error (Page Not Found) Page In Django 2.0'
Leave a comment:


*All Fields are mandatory. **Email Id will not be published publicly.


SUBSCRIBE
Please subscribe to get the latest articles in your mailbox.



Recent Posts:





© pythoncircle.com 2018-2019