Update 1: Please refer this updated article for Django 2.0 and source code.
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.
In this article we will discuss the third option.
You can ask user to subscribe or sign-up. Or you may show some funny stuff.
Default 404 error page in django is quite boring. Also creating a custom 404 page in django is very simple.
So lets see how to create custom 404 error page in django.
urls.py
file of your project, import handler404
and handler505
.urls.py
file import views from your app.urlpatterns
assign the views to handler404
and handler500
.
from myapp import views as myapp_views from django.conf.urls import handler404, handler500 urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^myapp/', include('myapp.urls', namespace='myapp')), ] handler404 = myapp_views.error_404 handler500 = myapp_views.error_500
settings.py
file, set DEBUG=False
and ALLOWED_HOST=["*"]
. Custom 404 and 500 pages works only when Debug is set to false and there is appropriate entry in allowed_hosts
.from django.shortcuts import render def error_404(request): data = {} return render(request,'myapp/error_404.html', data) def error_500(request): data = {} return render(request,'myapp/error_500.html', data)