Django: handler403 doesn't work, but 404 does
Asked Answered
I

3

5

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.

Intra answered 22/1, 2019 at 8:44 Comment(2)
Can you update your question with your custom error handler view ?Oberammergau
@MohammadUmair done.Intra
C
11

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.

Carnap answered 22/1, 2019 at 8:58 Comment(1)
Indeed! Thank you a lot :)Intra
I
3

If that's really your handler403 file (aka. handler403.py), you'll probably want

handler403 = 'general.views.handler403.handler403'

(so a dotted path to the actual callable).

Intelligent answered 22/1, 2019 at 8:52 Comment(2)
Nope, it doesn't help, I already tried to specify path in different ways. Also, to be precise, handler403 is stored in general.view.handler403, and general.view.__init__ has from .handler403 import handler403.Intra
You may want to hack in some debug instrumentation (that is, prints) into your local copy of django.urls.resolvers.URLResolver#resolve_error_handler, to see what it's trying to do.Intelligent
O
-2

handler403 should point to a view

Try something like this:

from general.views.handler403 import handler403

handler403 = handler403
Oberammergau answered 22/1, 2019 at 8:54 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.