Search code examples
pythondjangoviewdecoratorpermission-denied

Send Custom message in Django PermissionDenied


I am using django's PermissionDenied to render 403.html whenever the user is not allowed to access any page.

There are whole lot of pages, of different type, for example, Product page, User Page, User Contact information, Owner Information.

I would like to add the custom message with PermissionDenied, that would tell the user exactly why he can not view this page. I would like to add the following dynamic message to the 403.html.

You have are trying to `View a Product (id:3094384)` while having a `Trail` account. You are not authorized to view this product. 

And

 You have are trying to `View a Customer (id:48)` which is Private. You are not authorized to view this User. 

and so on.

here is my code

elif role.id == Project.ROLE_SALES and not project.sales_person_id == user_id:
            raise PermissionDenied

html

<body class="error-page">

<!--  content -->
<section>
    <div class="error403">
        <h1>403</h1>
    </div>
    <p class="description">Oops! Request forbidden...</p>

    <p>Sorry, it appears the page you were looking for is forbidden and not accessible. If the problem persists, please
        contact web Administrator.</p>


# HERE I WANT TO SHOW DYNAMIC MESSAGE. 



    <a href="{{ request.META.HTTP_REFERER }}" class="btn btn-danger403 btn-primary btn-large" >
        Go Back </a>
{{ except }}
</section>



<script src="{% static 'js/jquery.min.js' %}"></script>
<script src="{% static 'js/bootstrap.js' %}"></script>
</body>

Possibility

raise PermissionDenied("Custom message")

Or

Pass a context to PermissionDenied?

Suggestions.


Solution

  • This answer is probably arriving very late for you. But here it is. You can use this in your Django code:

    raise PermissionDenied("Custom message")
    

    And then display the custom message using below snippet in the 403.html template:

    {% if exception %}
      <p>{{ exception }}</p>
    {% else %}
      <p>Static generic message</p>
    {% endif %}

    The message string passed to 'PermissionDenied' is available in template context as explained in Django documentation - https://docs.djangoproject.com/en/stable/ref/views/#http-forbidden-view