8

I have simple middleware which checks if the HTML in the response is valid or not.

If the HTML is not valid an html is not valid" exception gets raised in development systems.

Up to now the xception contains the URL and the validation error.

Then the developer sees the URL in the well known yellow and gray django debug page.

Maybe I am blind, but if I look at the django debug page, I can't see which of my methods/views created the content with the broken html.

Is there a way to add more information to the "html is not valid" exception, to assist the developer? The developer should find the relevant method/view easier.

guettli
  • 25,042
  • 81
  • 346
  • 663
  • Django in debug mode provides a full stack trace of the error – at14 Jan 15 '18 at 09:33
  • @at14 yes, the debug page does provide the full stack trace to the line where the validation error gets created. But I need the place where the broken html was created. – guettli Jan 15 '18 at 09:57
  • 2
    Not exactly an answer to your question, but you can usually find the Python path of the view in the "Request" panel of Django Debug Toolbar – Daniel Hepper Jan 24 '18 at 08:00
  • Related: https://github.com/guettli/django-check-html-middleware – guettli May 01 '21 at 19:42

2 Answers2

3

The process_view hook gives you access to the view function, args, and kwargs. You could store these on the request, and then use them when you raise your "html is not valid" exception.

Alasdair
  • 298,606
  • 55
  • 578
  • 516
2

You could use process_view as Alasdair mentioned, initialize a dictionary for your debug messages and display them with the information needed.

You could also group the dictionary (self.debug_helper['process_request'] = {}') like below to specify detailed information of the Request/Response.

__module__ will give you the module in which the view function/class was defined.

class CheckForBrokenHtmlMiddleware(MiddlewareMixin):

    def __init__(self, get_response):
        self.get_response = get_response
        self.debug_helper = {}

    def process_request(self, request):
        self.debug_helper = {}
        self.debug_helper['process_request'] = {}
        self.debug_helper['process_request']['path'] = request.path

    def process_view(self, request, view_func, view_args, view_kwargs):
        self.debug_helper['name'] = view_func.__name__
        self.debug_helper['module'] = view_func.__module__
        self.debug_helper['message'] = '"{0}" view caused an error in module "{1}"'.format(
            view_func.__name__, view_func.__module__
        )

    def process_response(self, request, response):            
        print(self.debug_helper)
        return response
jazz
  • 2,371
  • 19
  • 23