0

I have an a django app for which I am writing middleware for. In the middleware, I have process_exception function where I have a the request object which is a WSGI Request object.

I want to get the view that the request has passed through. How can I do that?

If I try request.view, I get:

AttributeError: 'WSGIRequest' object has no attribute 'view'

I would further like to get model, serializer being used in that view but ofcourse I can do that using getattr easily once I get the view.

sshussain270
  • 1,785
  • 4
  • 25
  • 49
  • Possibly useful info: https://stackoverflow.com/questions/2491605/how-to-get-the-current-url-name-using-django – Ralf Jan 20 '21 at 13:34
  • Possibly useful info: https://stackoverflow.com/questions/46989848/django-get-name-of-current-view-as-a-string – Ralf Jan 20 '21 at 13:35
  • Possibly useful info: https://stackoverflow.com/questions/3081327/get-view-function-from-request-uri/3081361 – Ralf Jan 20 '21 at 13:35

1 Answers1

0

Although the request does not have an attribute indicating it's view you can get that as follows:

from django.urls import resolve

class MyMiddleware:
    def process_exception(self, request, exception):
        # code
        resolver_match = resolve(request.path_info)
        view_function = resolver_match.func # matching view function
        url_name = resolver_match.url_name # name of the matching url
        # code

Referred from the documentation resolve, ResolverMatch, attributes of HttpRequest (path_info)

Abdul Aziz Barkat
  • 19,475
  • 3
  • 20
  • 33