How to display "permission_denied_message" in custom 403.html page in Django

Viewed 326

How do we correctly display exception message in custom 403 error in Django?

In my signup view I am using:

class SignUpView(LoginRequiredMixin, PermissionRequiredMixin, CreateView):
    login_url = 'error_403'
    # ....
    # ...
    permission_denied_message = 'You are not allowed this transaction!! Ha Ha!!'
#    raise PermissionDenied() # ('permission_denied_message')
    raise_exception = True

Now how do I display the message ("permission_denied_message"?) in my custom 403.html?

This is my function to render the error page:

def error_403(request, exception):
    data = {}
    add_user = 'add_user'
    data = {'perm': add_user}
    return render(request, '403.html', data)

I have been through a lot of matter on the subject (including those on SO) but could not succeed in displaying the error message (except the static message that I have put in my "403.html"). I have used {{ exception}} in the template but nothing gets displayed (execpt the static message that I already have).

1. How do I display the permission_denied_message in custom 403 page?

2. Presently I am manually updating some raw data in dict data{} in function error_403, which gets rendered on the 403 error page. What is the correct usage of the dict?

1 Answers

You can use django messages framework to perform this. This allows you to add custom messages you want to send to the template. You need to import it from django.contrib. Here is the code to send an error message to the template.

from django.contrib import messages
# In your function you do this


def error_403(request, exception):
    error_message = messages.add_message(request, messages.ERROR, "permission denied")
    errors = {'errors': error_message}
    return render(request, '403.html', errors)

In your template you can check if there are error messages and then display them

<h1> {{errors}} </h1>
Related