[Fixed]-Send Custom message in Django PermissionDenied

27👍

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/1.10/ref/views/#http-forbidden-view

2👍

I came across the same issue and resolved it using the Django messages framework to pass a custom message to the template.

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

My specific example:

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

The messages can then be output in the template as described in the documentation.

1👍

You can try like this:

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")

Another way of sending a message to template is like:

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>
👤ruddra

1👍

If you are using class based views (CBV), or anything that extends the AccessMixin, either set the permission_denied_message attribute, or override the get_permission_denied_message method.

Example:

from django.conf import settings

class MyView(ListView):
    permission_denied_message = 'Hooo!'

    def get_permission_denied_message(self):
        perms = self.get_permission_required()
        if settings.DEBUG:
            for perm in perms:
                if not self.request.user.has_perm(perm):
                    return 'Permission denied: ' + str(perm)
        return ''

and then, in your template:

{% if exception and debug %}
    <h3 class="font-bold">{{ exception }}</h3>
{% endif %}
👤mehmet

0👍

Same issue here.

In django 1.9 we have this built in. In earliest django version we can use sys.exc_info(), so the next step is just reuse whole default permission_denied handler to 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 }}
...
👤proxy

Leave a comment