Django Guardian - How to use decor_required decorator with a class?

I have a CB DeleteView that I am trying to decorate with the permission of Guardian_required. Permission must be for the registered user and for the DeleteView object. Guardian docs are not too clear, so I wonder if anyone can clarify.

+6
source share
2 answers

I ran into almost the same problem, and here is my solution (adapted to your case):

views.py

class MyModelDeleteView(DeleteView): model=MyModel @method_decorator(permission_required_or_403('myapp.delete_mymodel', (MyModel, 'slug', 'slug'), accept_global_perms=True)) def dispatch(self, *args, **kwargs): return super(MyModelDeleteView, self).dispatch(*args, **kwargs) 

Please note that you can pass the accept_global_perms parameter, i.e. False by default. It allows users with 'myapp.delete_mymodel' to allow deletion of any object of the MyModel class. This can be useful, for example, for moderators.

Documentation of custodians Decorators .

+4
source

To decorate each instance of a view class, you need to decorate the class definition itself. To do this, you apply the decorator to the dispatch () method of the class. For xample

 class ExampleView(TemplateView): template_name = 'Example.html' @method_decorator(login_required) def dispatch(self, *args, **kwargs): return super(ExampleView, self).dispatch(*args, **kwargs) 
0
source

Source: https://habr.com/ru/post/917498/


All Articles