Django Custom Permission method or decorator

You can wrap the logic in a decorator:

from django.core.exceptions import PermissionDenied
from functools import wraps

def requires_company(view):
    @wraps(view)
    def _view(request, *args, **kwargs):
        if not Company.objects.filter(owner_id=request.user.id).exists():    
            raise PermissionDenied
        return view(request, *args, **kwargs)
    return _view

Then you use the decorator with:

@login_required
@requires_company
def only_company_can_view(request):
    # … rest of the logic …
    return render(request, 'template.html')

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top