Send custom message to Django PermissionDenied

I use django PermissionDeniedfor rendering 403.htmlwhen the user is not allowed access to any page.

There are many different types of pages, for example Product page, User Page, User Contact information, Owner Information.

I would like to add a custom post with PermissionDeniedthat would definitely tell the user why he cannot view this page. I would like to add the following dynamic post to 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. 

etc.

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>

Opportunity

raise PermissionDenied("Custom message")

or

Pass the context to PermissionDenied?

Suggestions.

+4
source share
4

, , . . Django:

raise PermissionDenied("Custom message")

, 403.html:

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

, "PermissionDenied", , Django - https://docs.djangoproject.com/en/1.10/ref/views/#http-forbidden-view

+6

Django, .

https://docs.djangoproject.com/en/1.8/ref/contrib/messages/

:

from django.contrib import messages
...
messages.error(request, 'The submission deadline has passed.')
raise PermissionDenied

, .

+1

:

class SomeException(Exception):
    message = 'An error occurred.'

    def __init__(self, message):
        self.message = message

    def __str__(self):
        return repr(self.message)

#usage
 raise SomeException("Hello, you have an exception here")

:

if not request.user.is_staff: #or your condition
   context['flash_message']= "permission error occurred"
   retrun render_to_response('template.html', context)

# template
<!-- I am using bootstrap here -->
<div class="alert alert-{{ flash_message_type }} flash_message hide">
    {{ flash_message | safe }}
</div>

<script>
...
if($.trim($(".flash_message").html()) != ''){
        $(".flash_message").slideDown();
        setTimeout(function(){
            $(".flash_message").slideUp();
        }, 5000);
    };
</script>
0

.

In django 1.9 we have this inline . In the earlier version of django, we can use it sys.exc_info(), so the next step is to simply reuse the entire default handler permission_deniedto add our exception.

# urls.py
...
handler403 = 'project.views.errors.permission_denied'
...

# views/errors.py
import sys

from django import http
from django.template import Context, TemplateDoesNotExist, loader
from django.views.decorators.csrf import requires_csrf_token


@requires_csrf_token
def permission_denied(request, template_name='403.html'):
    _, value, _ = sys.exc_info()

    try:
        template = loader.get_template(template_name)
    except TemplateDoesNotExist:
        return http.HttpResponseForbidden('<h1>403 Forbidden</h1>', content_type='text/html')
    return http.HttpResponseForbidden(
        template.render(request=request, context={'exception': force_text(value)})
    )

# templates/403.html
...
{{ exception }}
...
0
source

All Articles