Last modified: Jan 10, 2023 By Alexander Williams
How to Use Django HttpResponseBadRequest
Django HttpResponseBadRequest is a subclass of HttpResponse that returns an HTTP response with 400 status (bad requests).
In this tutorial, we'll learn how to use HttpResponseBadRequest with simple examples.
1. Using HttpResponseBadRequest with examples
first, we need to import HttpResponseBadRequest:
from django.http import HttpResponseBadRequest
example:
In the following example, we'll write a simple view that returns a response with 400 status Code.
def bad_request(request): return HttpResponseBadRequest("We cannot process the request")
output:
request's status:
You can also use HTML content with HttpResponseBadRequest:
def bad_request(request): return HttpResponseBadRequest("<h1>We cannot process the request</h1>")
Output:
Page's source:
4. How to solve HttpResponseBadRequest is not defined
issue's output:
To solve this issue, you need to import the subclass before your view like:
from django.http import HttpResponseBadRequest