Aseem
Aseem

Reputation: 6769

Django permission's specific to templateview

How to create multiple permission classes that would restrict user from accessing a template view ( that doesnt use any model). For example: I have 4 user categories - ( admin, management, principal, teacher). I have a Admin dashboard template view which should be restricted to user type=Admin.

I would like to be able to write multiple permission classes, which I can then use in combination in any view.

Following code generates 403 error:

class AdministratorPermission(AccessMixin):
    def has_permission(self):
        return True


class GeneralPerm1(AccessMixin):
    def has_permission(self):
        return True


class DashboardView(PermissionRequiredMixin,
                    LoginRequiredMixin, TemplateView):
    template_name = 'administrator/dashboard.html'
    permission_required = (AdministratorPermission,GeneralPerm1)

Is there a way to do something like DRF permissions.

Thanks

Upvotes: 0

Views: 1748

Answers (1)

Aseem
Aseem

Reputation: 6769

Permission1Mixin.py:

from django.contrib.auth.mixins import AccessMixin
from django.core.exceptions import PermissionDenied

class IsAdministratorMixin(AccessMixin):
    """ if user is not administrator, decline permission """

    def dispatch(self, request, *args, **kwargs):
        """
        if user is authenticated and administrator
            we are good. otherwise permission denied
        """
        if request.user.is_authenticated and \
                request.user.category.category == \
                UserCategoryEnum.ADMINISTRATOR.value:
            return super().dispatch(request, *args, **kwargs)

        raise PermissionDenied('Permission denied')  # decline permission

view.py

class DashboardView(IsAdministratorMixin, TemplateView):
    template_name = 'administrator/dashboard.html'

This way we can create multiple independent permission mixins and use them in combination.

Upvotes: 1

Related Questions