This
This

Reputation: 121

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

Upvotes: 4

Views: 18486

Answers (2)

solarissmoke
solarissmoke

Reputation: 31404

The mixin doesn't support OR conditions by default, but you can simply override the has_permission() method to do the permission checks yourself. Something like:

def has_permission(self):
    user = self.request.user
    return user.has_perm('polls.can_open') or user.has_perm('polls.can_edit')

Upvotes: 5

Ykh
Ykh

Reputation: 7717

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.

Upvotes: 6

Related Questions