I made custom 404 page in django. And I'm trying to get 404 error page intentionally.
myproject/urls.py:
from website.views import customhandler404, customhandler500, test
urlpatterns = [
re_path(r'^admin/', admin.site.urls),
re_path(r'^test/$', test, name='test'),
]
handler404 = customhandler404
handler500 = customhandler500
website/views.py
def customhandler404(request):
response = render(request, '404.html',)
response.status_code = 404
return response
def customhandler500(request):
response = render(request, '500.html',)
response.status_code = 500
return response
def test(request):
raise Http404('hello')
But when I go 127.0.0.1:8000/test/ , It seems to return 500.html
And terminal says:
[24/Mar/2018 22:32:17] "GET /test/ HTTP/1.1" 500 128
How can I intentionally get 404 page?
The Http404 exception In order to show customized HTML when Django returns a 404, you can create an HTML template named 404. html and place it in the top level of your template tree. This template will then be served when DEBUG is set to False .
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.
When you set debug to False, you don't have a custom handler, and the status code of the response is 404, the 404.html (if present) in your base template directory is used. To return a response with a 404 status, you can simply return an instance of django.http.HttpResponseNotFound
. The reason you got a 500 is because you raised an error instead of returning a response. So, your test function can be simply modified to this
from django.http import HttpResponseNotFound
def test(request):
return HttpResponseNotFound("hello")
Update:
So it turned out that the reason you are getting a 500 error was not that you raised an exception, but having incorrect function signatures. When I answered this question more than half a year ago I forgot that django catches HTTP404 exception for you. However, the handler view has different signatures than the normal views. The default handler for 404 is defaults.page_not_found(request, exception, template_name='404.html')
, which takes 3 arguments. So your custom handler should actually be
def customhandler404(request, exception, template_name='404.html'):
response = render(request, template_name)
response.status_code = 404
return response
Although, in this case, you may as well just use the default handler.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With