Send Custom message in Django PermissionDenied
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
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.
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>