How do I raise a Response Forbidden in django

前端 未结 4 1125
情深已故
情深已故 2020-12-12 23:09

I\'d like to do the following:

raise HttpResponseForbidden()

But I get the error:

exceptions must be old-style classes or d         


        
4条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-12 23:39

    You can optionally supply a custom template named "403.html" to control the rendering of 403 HTTP errors.

    As correctly pointed out by @dave-halter, The 403 template can only be used if you raise PermissionDenied

    Below is a sample view used to test custom templates "403.html", "404.html" and "500.html"; please make sure to set DEBUG=False in project's settings or the framework will show a traceback instead for 404 and 500.

    from django.http import HttpResponse
    from django.http import Http404
    from django.core.exceptions import PermissionDenied
    
    
    def index(request):
    
        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)
    

提交回复
热议问题