2

Im trying to make a custom handler for page 404 but I've got this error. Ive tried numerous ways around it but my view just doesnt seem to work?

handler404 = 'DEMOPROJECT.views.handler404'
handler500 = 'DEMOPROJECT.views.handler500'

def handler404(request, exception, template_name="404.html"):
    response = render_to_response('/not-found')
    response.status_code = 404
    return render(request, response)

def handler500(request, exception, template_name="500.html"):
    response = render_to_response('/not-found')
    response.status_code = 500
    return render(request, response)
ERRORS:
?: (urls.E007) The custom handler500 view 'DEMOPROJECT.views.handler500' does not take the correct number of arguments (request).

System check identified 1 issue (0 silenced).
Joelad
  • 492
  • 3
  • 12

1 Answers1

7

Depending on the version of Django they use, the views receive each other. In the official documentation you can consult the reduced parameters.

It would look like this, for a Django > 2.0:

def handler404(request, exception, template_name="404.html"):
    response = render_to_response(template_name)
    response.status_code = 404
    return response

def handler500(request, *args, **argv):
    return render(request, '500.html', status=500)

A possible simpler solution, if you do not intend to modify the context of the view, is to directly create the corresponding templates. By default, they use these templates if they can find them, respectively: 404.html, 500.html, 403.html, and 400.html.

And you must place them in template directory, as you can see below.

mysite/
    mysite/
        __init__.py
        settings.py
        ...
    polls/
        urls.py
        view.py
        ...
    templates/
        404.html
        500.html
    manage.py

In addition, this question is duplicated.

John
  • 770
  • 1
  • 9
  • 18
  • Create templates directly and skip the custom handler, make sure you have the `TEMPLATE_DIRS` set in your settings.py – John Mar 03 '20 at 13:44
  • What do you mean? – Joelad Mar 03 '20 at 13:49
  • 1
    If your goal is to show an HTML page when get the 404, 500 error, you can directly create the template with the name `404.html` or `500.html`. Django is going to look for the template with that name. – John Mar 03 '20 at 14:00
  • Then the code I wrote above will work, otherwise, specify which Django version you use. – John Mar 03 '20 at 14:08
  • I got it working. I made an html file called 404 and used `Template.as_view` and had to use `python manage.py runserver --insecure` to view it – Joelad Mar 04 '20 at 09:20