Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return 404 page intentionally in django

Tags:

django

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?

like image 453
touchingtwist Avatar asked Mar 24 '18 13:03

touchingtwist


People also ask

How do I return a 404 in Django?

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 .

How do I show 404 in Django?

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.


1 Answers

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.

like image 117
Mia Avatar answered Sep 20 '22 21:09

Mia