How do I raise a Response Forbidden in django

Django

Django Problem Overview


I'd like to do the following:

raise HttpResponseForbidden()

But I get the error:

exceptions must be old-style classes or derived from BaseException, not HttpResponseForbidden

How should I do this?

Django Solutions


Solution 1 - Django

if you want to raise an exception you can use:

from django.core.exceptions import PermissionDenied

def your_view(...):
    raise PermissionDenied()

It is documented here :

https://docs.djangoproject.com/en/stable/ref/views/#the-403-http-forbidden-view

As opposed to returing HttpResponseForbidden, raising PermissionDenied causes the error to be rendered using the 403.html template, or you can use middleware to show a custom "Forbidden" view.

Solution 2 - Django

Return it from the view as you would any other response.

from django.http import HttpResponseForbidden

return HttpResponseForbidden()

Solution 3 - Django

You can optionally supply a custom template named "403.html" to control the rendering of 403 HTTP errors.

As correctly pointed out by @dave-halter, The 403 template can only be used if you raise PermissionDenied

Below is a sample view used to test custom templates "403.html", "404.html" and "500.html"; please make sure to set DEBUG=False in project's settings or the framework will show a traceback instead for 404 and 500.

from django.http import HttpResponse
from django.http import Http404
from django.core.exceptions import PermissionDenied


def index(request):

    html = """
<!DOCTYPE html>
<html lang="en">
  <body>
    <ul>
        <li><a href="/">home</a></li>
        <li><a href="?action=raise403">Raise Error 403</a></li>
        <li><a href="?action=raise404">Raise Error 404</a></li>
        <li><a href="?action=raise500">Raise Error 500</a></li>
    </ul>
  </body>
</html>
"""

    action = request.GET.get('action', '')
    if action == 'raise403':
        raise PermissionDenied
    elif action == 'raise404':
        raise Http404
    elif action == 'raise500':
        raise Exception('Server error')

    return HttpResponse(html)

Solution 4 - Django

Try this Way , sending message with Error

from django.core.exceptions import PermissionDenied
raise PermissionDenied("You do not have permission to Enter Clients in Other Company, Be Careful")

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionocouttsView Question on Stackoverflow
Solution 1 - DjangoChrisView Answer on Stackoverflow
Solution 2 - DjangoIgnacio Vazquez-AbramsView Answer on Stackoverflow
Solution 3 - DjangoMario OrlandiView Answer on Stackoverflow
Solution 4 - DjangoSaad MirzaView Answer on Stackoverflow