Django:handler403 不起作用,但 404 起作用 [英] Django: handler403 doesn't work, but 404 does
问题描述
以下是 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'
如您所见,两个处理程序都指向同一个视图,而我最需要的第一个视图不起作用!例如,/obj/12
的其他用户的数据显示默认浏览器 403 页面:
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
[22/Jan/2019 08:39:14] "GET /obj/12 HTTP/1.1" 403 0
但第二个运行良好并显示正确的页面(当尝试访问 /obj/768
中的一些不存在的数据时).为什么以及如何解决?
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?
调试模式已关闭.我的 Django 版本是 2.0.6
The debug mode is off. My Django version is 2.0.6
更新.
handler403.py 文件的内容:
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
字符串 Handler 403 was called!
在我尝试获取此页面时从未打印过.
The string Handler 403 was called!
is never printed when I try to get this page.
推荐答案
我猜你的视图会返回一个 django.http.HttpResponseForbidden
而不是引发 django.core.exceptions.PermissionDenied
异常.
My guess is that your views returns a django.http.HttpResponseForbidden
instead of raising a django.core.exceptions.PermissionDenied
exception.
只有 PermissionDenied
异常被 handler403 处理,一个 HttpResponseForbidden
原样返回.
Only the PermissionDenied
exception gets handled by handler403, a HttpResponseForbidden
is returned as is.
这篇关于Django:handler403 不起作用,但 404 起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!