Default 404 handler. Templates: :template:`404.html` Context: request_path The path of the requested URL (e.g., '/app/pages/bad_page/'). It's quoted to prevent a content injection attack. exception The message from the exception which
(request, exception, template_name=ERROR_404_TEMPLATE_NAME)
| 33 | |
| 34 | @requires_csrf_token |
| 35 | def page_not_found(request, exception, template_name=ERROR_404_TEMPLATE_NAME): |
| 36 | """ |
| 37 | Default 404 handler. |
| 38 | |
| 39 | Templates: :template:`404.html` |
| 40 | Context: |
| 41 | request_path |
| 42 | The path of the requested URL (e.g., '/app/pages/bad_page/'). It's |
| 43 | quoted to prevent a content injection attack. |
| 44 | exception |
| 45 | The message from the exception which triggered the 404 (if one was |
| 46 | supplied), or the exception class name |
| 47 | """ |
| 48 | exception_repr = exception.__class__.__name__ |
| 49 | # Try to get an "interesting" exception message, if any (and not the ugly |
| 50 | # Resolver404 dictionary) |
| 51 | try: |
| 52 | message = exception.args[0] |
| 53 | except (AttributeError, IndexError): |
| 54 | pass |
| 55 | else: |
| 56 | if isinstance(message, str): |
| 57 | exception_repr = message |
| 58 | context = { |
| 59 | "request_path": quote(request.path), |
| 60 | "exception": exception_repr, |
| 61 | } |
| 62 | try: |
| 63 | template = loader.get_template(template_name) |
| 64 | body = template.render(context, request) |
| 65 | except TemplateDoesNotExist: |
| 66 | if template_name != ERROR_404_TEMPLATE_NAME: |
| 67 | # Reraise if it's a missing custom template. |
| 68 | raise |
| 69 | # Render template (even though there are no substitutions) to allow |
| 70 | # inspecting the context in tests. |
| 71 | template = Engine().from_string( |
| 72 | ERROR_PAGE_TEMPLATE |
| 73 | % { |
| 74 | "title": "Not Found", |
| 75 | "details": "The requested resource was not found on this server.", |
| 76 | }, |
| 77 | ) |
| 78 | body = template.render(Context(context)) |
| 79 | return HttpResponseNotFound(body) |
| 80 | |
| 81 | |
| 82 | @requires_csrf_token |