django User permissions and Permission Required Mixin

This picture This · Oct 25, 2017 · Viewed 9.2k times · Source

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')

Answer

Ykh picture Ykh · Oct 25, 2017

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.