[Fixed]-How to display the message passed to Http404 in a custom 404 Error template in Django?

14👍

As of Django 1.9, the exception is passed to the page_not_found view which runs when you raise Http404. A representation of the error is passed to the template, you can include it in your template with:

{{ exception }}

In earlier versions, the exception was not passed to the page_not_found view, so there wasn’t an easy way to include the message from the exception in the template.

One possibility was to use the messages framework as @Euribates suggests in their answer. Another was to render a template and return a 404 status code in your view, instead of raising Http404.

9👍

There is another way. The code at page_not_found uses RequestContext; that means that you have access to all the variables defined by all the context processors defined in the TEMPLATE_CONTEXT_PROCESSORS entry in settings.py. The default value includes, among others, the django messages framework.

So, you con define the message you want to show using messages.error, for example, and show the message in the template using the messages variable.

In other words, you can write your view like this:

from django.contrib import messages
from django.http import Http404
from django.template import RequestContext

def my_view(request):
    # your code goes here
    if something_horribly_wrong_happened():
        messages.error(request, 'Somethig horribly wrong happened!')
        raise Http404("It doesn't mind whatever you put here")
    else:
        return render_to_response(
            'template.html',
            RequestContext(request, locals()),
            )

In your 404.html template, you should write something like:

{% if messages %}
<ul class="messages">
    {% for message in messages %}
    <li>{{ message }}</li>
    {% endfor %}
</ul>
{% endif %}

It’s a bit more complex, but it has the advantage you can send several messages, and even use diferent kind of messages (Warning, Debug, Info, Error, etc…) You can read more about the django message framework here: The messages framework | Django Documentation.

1👍

I have simpler solution

Just write middleware, that would take your error text into some request variable. See example

from django.http.response import Http404

class Error404Middleware(object):
    def process_exception(self, request, exception):
        if isinstance(exception, Http404):
            request.error_404_message = exception.message

In 404.html

{{ request.error_404_message }}

0👍

{{ exception }}

As of 1.9.6, the message passed to:

raise Http404('msg')

is available from templates/404.html as:

{{ exception }}

Source: https://github.com/django/django/blob/1.9.6/django/views/defaults.py#L20

Leave a comment