Search code examples
pythondjangodjango-1.11

django User permissions and Permission Required Mixin


In this code, Django will check for all the permission in the tuple permission_required and if the user having all the permission get access to the view. I want to provide the view if the user having any permission in the given list or tuple. Eg: In this particular case if the user only having the polls.can_open permission I want to provide the view

from django.contrib.auth.mixins import PermissionRequiredMixin

class MyView(PermissionRequiredMixin, View)
    permission_required = ('polls.can_open', 'polls.can_edit')

Solution

  • MultiplePermissionsRequiredMixin in django-braces is what you need.

    the doc is here. Demo:

    from django.views.generic import TemplateView
    
    from braces import views
    
    
    class SomeProtectedView(views.LoginRequiredMixin,
                            views.MultiplePermissionsRequiredMixin,
                            TemplateView):
    
        #required
        permissions = {
            "all": ("blog.add_post", "blog.change_post"),
            "any": ("blog.delete_post", "user.change_user")
        }
    

    This view mixin can handle multiple permissions by setting the mandatory permissions attribute as a dict with the keys any and/or all to a list or tuple of permissions. The all key requires the request.user to have all of the specified permissions. The any key requires the request.user to have at least one of the specified permissions.