سؤال

I write a code like this in dispatch() of a view to constrain access to specific user:

if user.name != 'admin':
    raise PermissionDenied("you don't have access")

If the exception was raised, it just display on the redirected page of:

403 Forbidden

is it possible to let django display the error page with reason like:

403 Forbidden
you don't have access
هل كانت مفيدة؟

المحلول

You can do this using Django middleware with HttpResponseForbidden. It would look something like this:

from django.shortcuts import HttpResponseForbidden

class ForbiddenMiddleware(object):
    """
        Don't give permissions for particular without admin
    """
    def process_request(self, request):
        if not request.user.is_superuser:
           return HttpResponseForbidden("403 Forbidden , you don't have access")
        return None

Note: The above middleware applies for all views.

If you want to restrict the check to a particular view, do this:

def my_view(request, ):
    if not request.user.is_superuser:
      return HttpResponseForbidden("403 Forbidden , you don't have access")
    else:
        # your render

Update 2020

In Django 3.0, you have to import the HttpReponseForbidden class from http, like this:

from django.http import HttpResponseForbidden
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top