Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django middleware process_view get view class?

I am using classed based views and I want to create a middleware to redirect to other places under some conditions.

I have tried using process_request() but I will need to add exclusions to avoid loops.

What I am experimenting is to exclude views of a base view class, but process_view() gets view function, see documentation, it seems like I cannot get the view class from it, I am asking here to verify if that's true or there is a better way?

like image 366
James Lin Avatar asked May 19 '26 13:05

James Lin


1 Answers

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.

like image 125
knbk Avatar answered May 22 '26 10:05

knbk



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!