我想做以下几点:
raise HttpResponseForbidden()
但是我得到了一个错误:
exceptions must be old-style classes or derived from BaseException, not HttpResponseForbidden
我该怎么做呢?
我想做以下几点:
raise HttpResponseForbidden()
但是我得到了一个错误:
exceptions must be old-style classes or derived from BaseException, not HttpResponseForbidden
我该怎么做呢?
当前回答
如果你想引发一个异常,你可以使用:
from django.core.exceptions import PermissionDenied
def your_view(...):
raise PermissionDenied()
它被记录在这里:
https://docs.djangoproject.com/en/stable/ref/views/#the-403-http-forbidden-view
与返回HttpResponseForbidden相反,引发PermissionDenied会导致使用403.html模板呈现错误,或者你可以使用中间件显示一个自定义的“Forbidden”视图。
其他回答
您可以选择提供一个名为“403.html”的自定义模板来控制403个HTTP错误的呈现。
正如@dave-halter所正确指出的,403模板只能在引发PermissionDenied时使用
下面是一个用于测试自定义模板“403.html”,“404.html”和“500.html”的示例视图;请确保在项目的设置中设置DEBUG=False,否则框架将显示404和500的回溯。
from django.http import HttpResponse
from django.http import Http404
from django.core.exceptions import PermissionDenied
def index(request):
html = """
<!DOCTYPE html>
<html lang="en">
<body>
<ul>
<li><a href="/">home</a></li>
<li><a href="?action=raise403">Raise Error 403</a></li>
<li><a href="?action=raise404">Raise Error 404</a></li>
<li><a href="?action=raise500">Raise Error 500</a></li>
</ul>
</body>
</html>
"""
action = request.GET.get('action', '')
if action == 'raise403':
raise PermissionDenied
elif action == 'raise404':
raise Http404
elif action == 'raise500':
raise Exception('Server error')
return HttpResponse(html)
尝试这种方式,发送带有错误的消息
from django.core.exceptions import PermissionDenied
raise PermissionDenied("You do not have permission to Enter Clients in Other Company, Be Careful")
如果你想引发一个异常,你可以使用:
from django.core.exceptions import PermissionDenied
def your_view(...):
raise PermissionDenied()
它被记录在这里:
https://docs.djangoproject.com/en/stable/ref/views/#the-403-http-forbidden-view
与返回HttpResponseForbidden相反,引发PermissionDenied会导致使用403.html模板呈现错误,或者你可以使用中间件显示一个自定义的“Forbidden”视图。
从视图返回它,就像返回任何其他响应一样。
from django.http import HttpResponseForbidden
return HttpResponseForbidden()