Blog available for sell
This blog is available for sale. Please 'contact us' if interested.
Advertise with us
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 the home page, silently.
  • Show a boring 404 error page and then ask them to click on a link to go to the 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.

The 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 the 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 the 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 a 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 the project directory, there will be manage.py  file.

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

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

python manage.py startapp myapp


- This will add a new app to your project. The 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.


displaying custom 404 error page not found page in django

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


Code:

The code is available on Github. Please go through the 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.

3 comments on 'Displaying Custom 404 Error (Page Not Found) Page In Django 2.0'
Login to comment

Ali@Reza Dec. 17, 2018, 10:36 a.m.
Greetings!what's the problem !?please help me. TNXXXviews.py:def errors_404(request, exception): return render(request, 'error_404.html')note: even i checked: return render(request, 'django_sb_admin/error_404.html')#############urls.py:from django.conf.urls import handler404urlpatterns = [....]handler404 = "django_sb_admin.views.errors_404"note: even i checked: handler404 = "views.errors_404"####settings.py:DEBUG = FalseALLOWED_HOSTS = ['127.0.0.1']
David Jan. 30, 2019, 12:25 p.m.
Thanks man, you saved me.
Mouhssine Jan. 2, 2020, 1:39 p.m.
thanks for your help

Related Articles:
Solving Django Error: TemplateDoesNotExist at /app_name/
How to solve TemplateDoesNotExist error in Django projects, reason for TemplateDoesNotExist error in Django, fixing TemplateDoesNotExist error in Django...
Solving Django error 'NoReverseMatch at' URL with arguments '()' and keyword arguments '{}' not found.
Solving Django error 'NoReverseMatch at' URL with arguments '()' and keyword arguments '{}' not found, URL not found in Django, No reverse match in Django template error...
Designing custom 404 and 500 error pages in Django
How to create your own awesome 404 error or 500 error page in django. Step by step guide to help you design your own 404 not found error page in Django. Design your own 500 internal server error page in Django application...
DigitalOcean Referral Badge

© 2022-2023 Python Circle   Contact   Sponsor   Archive   Sitemap