一、返回错误响应

Django视图-LMLPHP

返回错误的3种方式:

中间件设置的属性:

Django的contrib应用程序中包含的一些中间件在请求中设置了属性。如果在请求中看不到该属性,请确保使用了相应的中间件类MIDDLEWARE

  • 返回 HttpResponseNotFound
  • 返回 HttpResponse 设置 status 状态码
  • 返回 Http404状态对象
    # 使用 HttpResponseNotFound
    def my_view(request):
      return HttpResponseNotFound('<h1>Page not found</h1>')
    
    
    # 还可以直接返回状态码
    from django.http import HttpResponse
    def my_view(request):
      return HttpResponse(status=201)
    
    
    # 特殊的 404  错误
    from django.http import Http404
    from django.shortcuts import render
    
    
    def detail(request, poll_id):
      raise Http404("Model does not exist")
      return HttpResponse('<h1>Page w
02-02 09:01