Custom 404 error view to handle translated error messages correctly

This commit is contained in:
Raphael Michel
2016-09-26 19:00:55 +02:00
parent 00810cdfab
commit 6d894bf98c
3 changed files with 28 additions and 1 deletions

View File

@@ -1,7 +1,9 @@
from django.http import HttpResponseForbidden
from django.http import HttpResponseForbidden, HttpResponseNotFound
from django.middleware.csrf import REASON_NO_CSRF_COOKIE, REASON_NO_REFERER
from django.template.loader import get_template
from django.utils.functional import Promise
from django.utils.translation import ugettext as _
from django.views.decorators.csrf import requires_csrf_token
def csrf_failure(request, reason=""):
@@ -30,3 +32,24 @@ def csrf_failure(request, reason=""):
"requests."),
}
return HttpResponseForbidden(t.render(c), content_type='text/html')
@requires_csrf_token
def page_not_found(request, exception):
exception_repr = exception.__class__.__name__
# Try to get an "interesting" exception message, if any (and not the ugly
# Resolver404 dictionary)
try:
message = exception.args[0]
except (AttributeError, IndexError):
pass
else:
if isinstance(message, str) or isinstance(message, Promise):
exception_repr = str(message)
context = {
'request_path': request.path,
'exception': exception_repr,
}
template = get_template('404.html')
body = template.render(context, request)
return HttpResponseNotFound(body)

View File

@@ -47,3 +47,5 @@ plugin_patterns = [
# The presale namespace comes last, because it contains a wildcard catch
urlpatterns = common_patterns + plugin_patterns + presale_patterns_main
handler404 = 'pretix.base.views.errors.page_not_found'

View File

@@ -40,3 +40,5 @@ plugin_patterns = [
# The presale namespace comes last, because it contains a wildcard catch
urlpatterns = common_patterns + plugin_patterns + presale_patterns
handler404 = 'pretix.base.views.errors.page_not_found'