Django display 404 on missing template

2019-06-16 08:45发布

问题:

I have a website where some pages are edited by hand. When one of those templates is missing, it just means that the page is not present, so I would like to display an Error 404.

Instead I get an exception TemplateDoesNotExist.

Is there a way to tell Django to display an error 404 whenever it does not find a template?

回答1:

If you want this behaviour for all views on your site, you might want to write your own middleware with a process_exception method.

from django.template import TemplateDoesNotExist
from django.views.defaults import page_not_found

class TemplateDoesNotExistMiddleware(object):
    """ 
    If this is enabled, the middleware will catch
    TemplateDoesNotExist exceptions, and return a 404
    response.
    """

    def process_exception(self, request, exception):
        if isinstance(exception, TemplateDoesNotExist):
            return page_not_found(request)

If you have defined your own handler404 you would need to replace page_not_found above. I'm not immediately sure how you could convert the string handler404 into the callable required in the middleware..

To enable your middleware, add it to MIDDLEWARE_CLASSES in settings.py. Be careful of the position where you add it. The standard Django middleware warning applies:

Again, middleware are run in reverse order during the response phase, which includes process_exception. If an exception middleware returns a response, the middleware classes above that middleware will not be called at all.



回答2:

put the return of the response in the view (or whereever the template is rendered) in a try-except block:

from django.http import Http404
from django.shortcuts import render_to_response
from django.template import TemplateDoesNotExist

def the_view(request):
    ...
    try:
        return render_to_response(...)
    except TemplateDoesNotExist:
        raise Http404


回答3:

Off the top of my head, but if you set DEBUG=False in your settings, won't you get a 404 then on every error (including TemplateNotFound)?