Coverage for benefits / views.py: 100%

33 statements  

« 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 

3 

4from benefits.core.middleware import index_or_agencyindex_origin_decorator, pageview_decorator 

5 

6 

7class BaseErrorView(TemplateView): 

8 """Base view class for HTTP error handlers.""" 

9 

10 status_code = 400 

11 

12 def __init__(self, **kwargs): 

13 super().__init__(**kwargs) 

14 self.template_name = self.template_name or f"{self.status_code}.html" 

15 

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) 

20 

21 def render_to_response(self, context, **response_kwargs): 

22 """ 

23 Inject the custom status code into the TemplateResponse. 

24 

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) 

32 

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) 

40 

41 

42class BadRequestView(BaseErrorView): 

43 """View handler for HTTP 400 Bad Request responses.""" 

44 

45 status_code = 400 

46 

47 

48class ForbiddenView(BaseErrorView): 

49 """View handler for HTTP 403 Forbidden responses. Returns a 403 response with the BadRequest template.""" 

50 

51 status_code = 403 

52 template_name = "400.html" 

53 

54 

55class CsrfFailureView(BaseErrorView): 

56 """View handler for CSRF_FAILURE_VIEW. Returns a 403 response with the BadRequest template.""" 

57 

58 status_code = 403 

59 template_name = "400.html" 

60 

61 

62def csrf_failure_handler(request, reason=""): 

63 """Wrapper function to satisfy CSRF_FAILURE_VIEW string resolution.""" 

64 return CsrfFailureView.as_view()(request, reason=reason) 

65 

66 

67class NotFoundView(BaseErrorView): 

68 """View handler for HTTP 404 Not Found responses.""" 

69 

70 status_code = 404 

71 

72 

73class ServerErrorView(BaseErrorView): 

74 """View handler for HTTP 500 Server Error responses.""" 

75 

76 status_code = 500 

77 

78 

79def server_error_handler(request): 

80 """Wrapper function to satisfy handler500 system check (urls.E007).""" 

81 return ServerErrorView.as_view()(request)