Coverage for benefits / views.py: 100%
33 statements
« prev ^ index » next coverage.py v7.13.4, created at 2026-02-13 19:35 +0000
« prev ^ index » next coverage.py v7.13.4, created at 2026-02-13 19:35 +0000
1from django.utils.decorators import method_decorator
2from django.views.generic import TemplateView
4from benefits.core.middleware import index_or_agencyindex_origin_decorator, pageview_decorator
7class BaseErrorView(TemplateView):
8 """Base view class for HTTP error handlers."""
10 status_code = 400
12 def __init__(self, **kwargs):
13 super().__init__(**kwargs)
14 self.template_name = self.template_name or f"{self.status_code}.html"
16 @method_decorator(pageview_decorator)
17 @method_decorator(index_or_agencyindex_origin_decorator)
18 def dispatch(self, request, *args, **kwargs):
19 return super().dispatch(request, *args, **kwargs)
21 def render_to_response(self, context, **response_kwargs):
22 """
23 Inject the custom status code into the TemplateResponse.
25 This is more idiomatic for CBVs than returning specialized subclasses
26 (like HttpResponseNotFound), as it allows TemplateView to handle
27 lazy rendering and context processors while ensuring the browser
28 receives the correct error status.
29 """
30 response_kwargs.setdefault("status", self.status_code)
31 return super().render_to_response(context, **response_kwargs)
33 def post(self, request, *args, **kwargs):
34 """
35 Handle POST requests by treating them as GET requests.
36 This prevents 405 errors when error handlers are triggered
37 by failed POST submissions (common with CSRF failures).
38 """
39 return self.get(request, *args, **kwargs)
42class BadRequestView(BaseErrorView):
43 """View handler for HTTP 400 Bad Request responses."""
45 status_code = 400
48class ForbiddenView(BaseErrorView):
49 """View handler for HTTP 403 Forbidden responses. Returns a 403 response with the BadRequest template."""
51 status_code = 403
52 template_name = "400.html"
55class CsrfFailureView(BaseErrorView):
56 """View handler for CSRF_FAILURE_VIEW. Returns a 403 response with the BadRequest template."""
58 status_code = 403
59 template_name = "400.html"
62def csrf_failure_handler(request, reason=""):
63 """Wrapper function to satisfy CSRF_FAILURE_VIEW string resolution."""
64 return CsrfFailureView.as_view()(request, reason=reason)
67class NotFoundView(BaseErrorView):
68 """View handler for HTTP 404 Not Found responses."""
70 status_code = 404
73class ServerErrorView(BaseErrorView):
74 """View handler for HTTP 500 Server Error responses."""
76 status_code = 500
79def server_error_handler(request):
80 """Wrapper function to satisfy handler500 system check (urls.E007)."""
81 return ServerErrorView.as_view()(request)