Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django Guardian - How to use a permission_required decorator with a class based view?

Tags:

django

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.

like image 955
Dmitriy Smirnov Avatar asked Jun 07 '12 03:06

Dmitriy Smirnov


1 Answers

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.

like image 67
Vlad T. Avatar answered Nov 15 '22 19:11

Vlad T.