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?
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.
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.
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.
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.
@method_decorator
takes a function as parameter. If you want to pass a decorator with parameters, you only need 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):
...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With