144π
Under your main views.py
add your own custom implementation of the following two views, and just set up the templates 404.html and 500.html with what you want to display.
With this solution, no custom code needs to be added to urls.py
Hereβs the code:
from django.shortcuts import render_to_response
from django.template import RequestContext
def handler404(request, *args, **argv):
response = render_to_response('404.html', {},
context_instance=RequestContext(request))
response.status_code = 404
return response
def handler500(request, *args, **argv):
response = render_to_response('500.html', {},
context_instance=RequestContext(request))
response.status_code = 500
return response
Update
handler404
and handler500
are exported Django string configuration variables found in django/conf/urls/__init__.py
. That is why the above config works.
To get the above config to work, you should define the following variables in your urls.py
file and point the exported Django variables to the string Python path of where these Django functional views are defined, like so:
# project/urls.py
handler404 = 'my_app.views.handler404'
handler500 = 'my_app.views.handler500'
Update for Django 2.0
Signatures for handler views were changed in Django 2.0:
https://docs.djangoproject.com/en/2.0/ref/views/#error-views
If you use views as above, handler404 will fail with message:
βhandler404() got an unexpected keyword argument βexception'β
In such case modify your views like this:
def handler404(request, exception, template_name="404.html"):
response = render_to_response(template_name)
response.status_code = 404
return response
112π
Official answer:
Here is the link to the official documentation on how to set up custom error views:
https://docs.djangoproject.com/en/stable/topics/http/views/#customizing-error-views
It says to add lines like these in your URLconf (setting them anywhere else will have no effect):
handler404 = 'mysite.views.my_custom_page_not_found_view'
handler500 = 'mysite.views.my_custom_error_view'
handler403 = 'mysite.views.my_custom_permission_denied_view'
handler400 = 'mysite.views.my_custom_bad_request_view'
You can also customise the CSRF error view by modifying the setting CSRF_FAILURE_VIEW
.
Default error handlers:
Itβs worth reading the documentation of the default error handlers, page_not_found
, server_error
, permission_denied
and bad_request
. By default, they use these templates if they can find them, respectively: 404.html
, 500.html
, 403.html
, and 400.html
.
So if all you want to do is make pretty error pages, just create those files in a TEMPLATE_DIRS
directory, you donβt need to edit URLConf at all. Read the documentation to see which context variables are available.
In Django 1.10 and later, the default CSRF error view uses the template 403_csrf.html
.
Gotcha:
Donβt forget that DEBUG
must be set to False for these to work, otherwise, the normal debug handlers will be used.
- [Django]-Django Queryset with year(date) = '2010'
- [Django]-How to define two fields "unique" as couple
- [Django]-Django override save for model only in some cases?
55π
Add these lines in urls.py
urls.py
from django.conf.urls import (
handler400, handler403, handler404, handler500
)
handler400 = 'my_app.views.bad_request'
handler403 = 'my_app.views.permission_denied'
handler404 = 'my_app.views.page_not_found'
handler500 = 'my_app.views.server_error'
# ...
and implement our custom views in views.py.
views.py
from django.shortcuts import (
render_to_response
)
from django.template import RequestContext
# HTTP Error 400
def bad_request(request):
response = render_to_response(
'400.html',
context_instance=RequestContext(request)
)
response.status_code = 400
return response
# ...
- [Django]-Django β filtering on foreign key properties
- [Django]-Access web server on VirtualBox/Vagrant machine from host browser?
- [Django]-Missing Table When Running Django Unittest with Sqlite3
46π
Django 3.0+ 4.0+
here is link how to customize error views
here is link how to render a view
in the urls.py
(the main one, in project folder), put:
handler404 = 'my_app_name.views.custom_page_not_found_view'
handler500 = 'my_app_name.views.custom_error_view'
handler403 = 'my_app_name.views.custom_permission_denied_view'
handler400 = 'my_app_name.views.custom_bad_request_view'
and in the mentioned app (my_app_name
) put in the views.py
:
def custom_page_not_found_view(request, exception):
return render(request, "errors/404.html", {})
def custom_error_view(request, exception=None):
return render(request, "errors/500.html", {})
def custom_permission_denied_view(request, exception=None):
return render(request, "errors/403.html", {})
def custom_bad_request_view(request, exception=None):
return render(request, "errors/400.html", {})
NOTE: errors/404.html
is the path if you place your files into the projects (not the apps) template foldertemplates/errors/404.html
so please place the files where you want and write the right path.
NOTE 2: After page reload, if you still see the old template, change in settings.py
DEBUG=True
, save it, and then again to False
and save again (that will restart the server and collect the new files).
- [Django]-Django REST Framework : "This field is required." with required=False and unique_together
- [Django]-Has Django served an excess of 100k daily visits?
- [Django]-How to stop autopep8 not installed messages in Code
23π
From the page you referenced:
When you raise Http404 from within a view, Django will load a special view devoted to handling 404 errors. It finds it by looking for the variable handler404 in your root URLconf (and only in your root URLconf; setting handler404 anywhere else will have no effect), which is a string in Python dotted syntax β the same format the normal URLconf callbacks use. A 404 view itself has nothing special: Itβs just a normal view.
So I believe you need to add something like this to your urls.py:
handler404 = 'views.my_404_view'
and similar for handler500.
- [Django]-How to write setup.py to include a Git repository as a dependency
- [Django]-Error when using django.template
- [Django]-Django β No module named _sqlite3
21π
In Django 3.x
, the accepted answer wonβt work because render_to_response
has been removed completely as well as some more changes have been made since the version the accepted answer worked for.
Some other answers are also there but Iβm presenting a little cleaner answer:
In your main urls.py
file:
handler404 = 'yourapp.views.handler404'
handler500 = 'yourapp.views.handler500'
In yourapp/views.py
file:
def handler404(request, exception):
context = {}
response = render(request, "pages/errors/404.html", context=context)
response.status_code = 404
return response
def handler500(request):
context = {}
response = render(request, "pages/errors/500.html", context=context)
response.status_code = 500
return response
Ensure that you have imported render()
in yourapp/views.py
file:
from django.shortcuts import render
Side note: render_to_response()
was deprecated in Django 2.x
and it has been completely removed in verision 3.x
.
- [Django]-Django: show the count of related objects in admin list_display
- [Django]-Altering one query parameter in a url (Django)
- [Django]-Invalid http_host header
19π
If all you need is to show custom pages which have some fancy error messages for your site when DEBUG = False
, then add two templates named 404.html and 500.html in your templates directory and it will automatically pick up this custom pages when a 404 or 500 is raised.
- [Django]-How do you Serialize the User model in Django Rest Framework
- [Django]-Reference list item by index within Django template?
- [Django]-Python Asyncio in Django View
17π
No additional view is required. https://docs.djangoproject.com/en/3.0/ref/views/
Just put the error files in the root of templates directory
- 404.html
- 400.html
- 403.html
- 500.html
And it should use your error page when debug is False
- [Django]-Getting Values of QuerySet in Django
- [Django]-Django Sitemaps and "normal" views
- [Django]-Django: How to format a DateField's date representation?
15π
settings.py:
DEBUG = False
TEMPLATE_DEBUG = DEBUG
ALLOWED_HOSTS = ['localhost'] #provide your host name
and just add your 404.html
and 500.html
pages in templates folder.
remove 404.html
and 500.html
from templates in polls app.
- [Django]-Make the first letter uppercase inside a django template
- [Django]-Django index page best/most common practice
- [Django]-Django create userprofile if does not exist
14π
In Django 2.* you can use this construction in views.py
def handler404(request, exception):
return render(request, 'errors/404.html', locals())
In settings.py
DEBUG = False
if DEBUG is False:
ALLOWED_HOSTS = [
'127.0.0.1:8000',
'*',
]
if DEBUG is True:
ALLOWED_HOSTS = []
In urls.py
# https://docs.djangoproject.com/en/2.0/topics/http/views/#customizing-error-views
handler404 = 'YOUR_APP_NAME.views.handler404'
Usually i creating default_app and handle site-wide errors, context processors in it.
- [Django]-How does Django's nested Meta class work?
- [Django]-How to understand lazy function in Django utils functional module
- [Django]-Invalid http_host header
7π
Make an error, on the error page find out from where django is loading templates. I mean the path stack. In base template_dir
add these html pages 500.html
, 404.html
. When these errors occur the respective template files will be automatically loaded.
You can add pages for other error codes too, like 400 and 403.
- [Django]-Django {% if forloop.first %} question
- [Django]-Django: Get model from string?
- [Django]-How do I integrate Ajax with Django applications?
5π
As one single line (for 404 generic page):
from django.shortcuts import render_to_response
from django.template import RequestContext
return render_to_response('error/404.html', {'exception': ex},
context_instance=RequestContext(request), status=404)
- [Django]-Name '_' is not defined
- [Django]-What does 'many = True' do in Django Rest FrameWork?
- [Django]-Disabled field is not passed through β workaround needed
5π
# views.py
def handler404(request, exception):
context = RequestContext(request)
err_code = 404
response = render_to_response('404.html', {"code":err_code}, context)
response.status_code = 404
return response
# <project_folder>.urls.py
handler404 = 'todo.views.handler404'
This works on django 2.0
Be sure to include your custom 404.html
inside the app templates folder.
- [Django]-How to do SELECT MAX in Django?
- [Django]-How do I get the class of a object within a Django template?
- [Django]-Check if celery beat is up and running
3π
Try moving your error templates to .../Django/mysite/templates/
.
I am note sure about this one, but I think these need to be "global" to the website.
- [Django]-How to disable Django's CSRF validation?
- [Django]-How do I integrate Ajax with Django applications?
- [Django]-How to show processing animation / spinner during ajax request?
1π
In Django root urls.py file, add the below lines
from django.conf.urls import (handler400, handler403, handler404, handler500)
handler400 = 'app.views.bad_request'
handler403 = 'app.views.permission_denied'
handler404 = 'app.views.page_not_found'
handler500 = 'app.views.server_error'
In your appβs views.py file, create the respective functions.
def server_error(request, exception=None):
# return render(request, '500.html')
return redirect('/')
Finally, in your settings.py file, set DEBUG = False
- [Django]-Django Installed Apps Location
- [Django]-Django character set with MySQL weirdness
- [Django]-Django-tables2: How to use accessor to bring in foreign columns?
1π
I had an additional
TEMPLATE_DIRS
within my settings.py
and that was causing the problem.
This answer was posted as an edit to the question Django, creating a custom 500/404 error page by the OP reZach under CC BY-SA 3.0.
- [Django]-Get protocol + host name from URL
- [Django]-Using JSON in django template
- [Django]-Can't compare naive and aware datetime.now() <= challenge.datetime_end
1π
Django > 2.2
from django.shortcuts import render_to_response, render
from django.template import RequestContext
def handler500(request, *args, **argv):
context = {}
print(request.body, '==========')
response = render(request, '500.jinja', context=context)
response.status_code = 500
return response
in urls.py
handler500 = 'apps.core.views.handler500'
- [Django]-How to Unit test with different settings in Django?
- [Django]-Django values_list vs values
- [Django]-Django TemplateSyntaxError β 'staticfiles' is not a registered tag library
0π
In urls.py
, enter this code:
from django.conf.urls import (handler400, handler403, handler404, handler500)
handler404 = 'my_app.views.page_not_found_view'
then add this code in your views.py
from django.shortcuts import render,get_object_or_404
def page_not_found_view(request, exception):
return render(request, '404.html', status=404)
Dont forget to set DEBUG = False
and also set ALLOWED_HOSTS = [127.0.0.1]
while you are testing in your laptop.
- [Django]-How to write setup.py to include a Git repository as a dependency
- [Django]-Where can I find the error logs of nginx, using FastCGI and Django?
- [Django]-Delete multiple objects in django
0π
You donβt need to do anything fancy, just create a 404.html
file in your templates. Go to settings.py
and set:
DEBUG = False
ALLOWED_HOSTS = ["*"]
It will automatically overwrite the default.
- [Django]-Whats the difference between using {{STATIC_URL}} and {% static %}
- [Django]-Django rest framework, use different serializers in the same ModelViewSet
- [Django]-How to update an existing Conda environment with a .yml file
0π
Easy Method:
To quickly create a custom error page for the 404
error, place a file named 404.html
in your root template directory. For other errors like 400
, 500
, and 403
, follow the same pattern by creating 400.html
, 500.html
, and 403.html
respectively in the same root template directory
Source: Django documentation on serving static files
Method 2:
To customize error pages in Django, follow these steps:
-
Open your Django root
urls.py
file. -
Add the following lines to associate specific views with different error codes:
from django.conf.urls import (handler400, handler403, handler404, handler500) handler400 = 'app.views.bad_request' handler403 = 'app.views.permission_denied' handler404 = 'app.views.page_not_found' handler500 = 'app.views.server_error'
Replace
'app.views.bad_request'
,'app.views.permission_denied'
,'app.views.page_not_found'
, and'app.views.server_error'
with the actual paths to your custom view functions for handling each error.
Source: Django documentation on customizing error views
Keep in mind that if the
DEBUG
setting in your configuration is set toTrue
, the custom404
page you create might not be displayed. Instead, Django will show the URL configuration along with debugging information.
- [Django]-Django edit user profile
- [Django]-What is the SQL ''LIKE" equivalent on Django ORM queries?
- [Django]-Django Rest Framework β Could not resolve URL for hyperlinked relationship using view name "user-detail"