[Django]-Django middleware process_view get view class?

4👍

By default there is indeed no way to get the actual view class. However, you can override the as_view method as follows:

class ViewClassMixin(object):
    @class_method
    def as_view(cls, **initkwargs):
        view = super(ViewClassMixin, cls).as_view(**initkwargs)
        view.cls = cls
        return view

Credits go to the django-rest-framework who use this method in their view classes.

Then the view class is accessible as the cls attribute on the actual view function.

Update: 1.9 will add the same behaviour to Django’s own class-based views. The view function returned by View.as_view() will have a view_class attribute.

👤knbk

1👍

A bit out of scope of my question:

Instead of excluding views of a base view class, I have opted for a decorator style like login_required

def skip_user_status_sync(view_func):
    """ marks the view function to skip sync middleware """
    view_func.skip_user_status_sync = True
    return view_func

in urls, like login_required:

url(r'^logout/$', skip_user_status_sync(views.Logout.as_view()), name='logout'),

then in middleware to inspect that function attribute:

class UserStatusSyncMiddleware(object):
    def process_view(self, request, view_func, *view_args, **view_kwargs):
        if hasattr(view_func, 'skip_user_status_sync'):
            return None

Leave a comment