Django returns error when trying to access request.sentry attribute


#1

I have custom views to handle 400, 403, 404, and 500 errors and I’m attempting to display the message reference to the user on the error page as detailed in the sentry documentation under Message References.

If I try to access request.sentry.id from my template, I get nothing unless I specifically pass request.sentry in the page context. The issue is that when I then force a “404 Page Not Found” error by navigating to a known invalid url, a “500 Server Error” is returned with the error AttributeError: 'WSGIRequest' object has no attribute 'sentry'. The odd part is that on the “500” error page, it displays a message reference, suggesting that request did have a sentry attribute which in turn had a valid id attribute.

I’m not sure if this is because I’m not passing the request parameter correctly to the view or something similar. That seems unlikely since I can access self.request from the view so maybe it’s that I’m trying to access the sentry attribute too early. I’ve included my code for my error views and the relevant urls.py segment below.

As an addendum, adding or removing the SentryResponseErrorIdMiddleware has no effect either way.

class GenericError(generic.TemplateView):
    template_name = "error.html"

    def __init__(self):
        self.error_value = 0
        self.error_type = "Error"

    def get_context_data(self, **kwargs):
        context = super(GenericError, self).get_context_data(**kwargs)
        context["error_value"] = f"{self.error_value!s}"
        context["error_type"] = self.error_type
        context["sentry"] = self.request.sentry
        return context

    def render_to_response(self, context, **response_kwargs):
        response = super(GenericError, self).render_to_response(context, **response_kwargs)
        response.status_code = self.error_value
        return response

class PageNotFound(GenericError):
    def __init__(self):
        self.error_value = 404
        self.error_type = "Page Not Found"
handler404 = views.PageNotFound.as_view()

I’ve tried to debug this for about two days now and had little success so I’m hoping it’s something that someone else has come across before.