Search code examples
pythondjangoserverhttp-status-code-403

Django: handler403 doesn't work, but 404 does


Here is content of MyProj/urls.py:

from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('general.urls')), # Main app
]

handler403 = 'general.views.handler403'
handler404 = 'general.views.handler403'

As you can see, both handlers point to the same view, and first one, which I need most, doesn't work! For example, data of other's user at /obj/12 shows default browser 403 page:

[22/Jan/2019 08:39:14] "GET /obj/12 HTTP/1.1" 403 0

But the second one works well and shows correct page (when try to access some not existing data at /obj/768). Why and how can I solve it?

The debug mode is off. My Django version is 2.0.6

Update.

Content of the handler403.py file:

from django.shortcuts import render_to_response

def handler403(request, *args, **argv):
    print('Handler 403 was called!')
    u = request.user
    params = {
        'user': u,
    }
    response = render_to_response('403.html', params)
    response.status_code = 403
    return response

The string Handler 403 was called! is never printed when I try to get this page.


Solution

  • My guess is that your views returns a django.http.HttpResponseForbidden instead of raising a django.core.exceptions.PermissionDenied exception.

    Only the PermissionDenied exception gets handled by handler403, a HttpResponseForbidden is returned as is.