I was trying to write custom error pages and got this issue, when a user is not authenticated and tries to visit a specific webpage I returned PermissionDenied() handler to show a 403(expected by me) but, django shows a 500 error instead. How do I show a 403 error in this case?
My urls.py:
handler404 = 'error.views.error_404'
handler403 = 'error.views.error_403'
handler500 = 'error.views.error_500'
handler400 = 'error.views.error_400'
My views.py to authenticate the user:
if request.user.is_authenticated():
return render(request,"app/index.html")
else:
return PermissionDenied()
My views.py used to handle exceptions:
def error_404(request, exception):
data = {}
return render(request,'error/404.html', data)
def error_403(request, exception):
data = {}
return render(request,'error/403.html', data)
def error_500(request):
data = {}
return render(request,'error/500.html', data)
def error_400(request, exception):
data = {}
return render(request,'error/400.html', data)
Reference Used: How do I raise a Response Forbidden in django
You should raise PermissionDenied
[Django-doc] as an exception, so:
if request.user.is_authenticated():
return render(request,"app/index.html")
else:
raise PermissionDenied()
or you can return a HttpResponseForbidden
[Django-doc]:
from django.http import HttpResponseForbidden
if request.user.is_authenticated():
return render(request,"app/index.html")
else:
return HttpResponseForbidden()
but you can not merge the two and return a PermissionDenied
, or raise
a HttpResponseForbidden
: PermissionDenied
is an exception whereas HttpResponseForbidden
is a HTTP response.