6

I have a CB DeleteView that I am trying to decorate with Guardian's permission_required. The permission should be for the logged in user and for the object of the DeleteView. The Guardian docs aren't too clear about this, so I'm wondering if anyone could clarify.

Dmitriy Smirnov
  • 449
  • 4
  • 15
  • Your question is similar to this one, check it out. http://stackoverflow.com/questions/6069070/how-to-use-permission-required-decorators-on-django-class-based-views – Johnny Zhao Oct 12 '12 at 10:05

2 Answers2

5

I encountered 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)

Note that you can pass accept_global_perms parameter, that is False by default. It allows users with 'myapp.delete_mymodel' permission to delete any object of MyModel class. This can be useful for moderators, for example.

Guardian Decorators documentation.

Vlad T.
  • 2,568
  • 3
  • 26
  • 40
  • 1
    Updated guardian decorators documentation link [here](http://django-guardian.readthedocs.io/en/stable/userguide/check.html#using-decorators) – Shadi Apr 20 '18 at 08:35
0

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.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)
Vivek S
  • 5,384
  • 8
  • 51
  • 72
  • 1
    I am aware of this. However, I am specifically asking how to include the user and the model object in the Guardian permission decorator in a CBV. Thanks! – Dmitriy Smirnov Jun 07 '12 at 04:35