Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function decorators with parameters on a class based view in Django

The official documentation explains how to decorate a class based view, however I could not find any information on how to provide parameters to the decorator.

I would like to achieve something like

class MyView(View):
    @method_decorator(mydecorator, some_parameters)
    def dispatch(self, *args, **kwargs):
        return super(MyView, self).dispatch(*args, **kwargs)

which should be equivalent to

@mydecorator(some_parameters)
def my_view(request):
    ....

How do I deal with such cases?

like image 293
Buddyshot Avatar asked Jan 09 '15 14:01

Buddyshot


People also ask

How do you use decorators in class-based views django?

You need to apply the decorator to the dispatch method of the class based view. This can be done as follows: class ProfileView(View): @youdecorator def dispatch(self,request,*args,**kwargs): return super(ProfileView,self). dispatch(request,*args,**kwargs) //Rest of your code.

How do you add decorators in class-based view?

To decorate every instance of a class-based view, you need to decorate the class definition itself. To do this you apply the decorator to the dispatch() method of the class. The decorators will process a request in the order they are passed to the decorator.

Which is better class-based view or function based view django?

Class based views are excellent if you want to implement a fully functional CRUD operations in your Django application, and the same will take little time & effort to implement using function based views.

What is the difference between function based and class-based views?

Class-based views are the alternatives of function-based views. It is implemented in the projects as Python objects instead of functions. Class-based views don't replace function-based views, but they do have certain advantages over function-based views.


1 Answers

@method_decorator takes a function as parameter. If you want to pass a decorator with parameters, you only need to:

  • Evaluate the parameters in the decorator-creator function.
  • Pass the evaluated value to @method_decorator.

In explicit Python code this would be:

decorator = mydecorator(arg1, arg2, arg...)
method_dec = method_decorator(decorator)

class MyClass(View):
    @method_dec
    def my_view(request):
        ...

So, using the syntactic sugar completely:

class MyClass(View):
    @method_decorator(mydecorator(arg1, arg2, arg...))
    def my_view(request):
        ...
like image 157
Luis Masuelli Avatar answered Sep 27 '22 19:09

Luis Masuelli