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:

How to Use Django HttpResponseBadRequest

request's status:

How to Use Django HttpResponseBadRequest

You can also use HTML content with HttpResponseBadRequest:

def bad_request(request):
    return HttpResponseBadRequest("<h1>We cannot process the request</h1>")

Output:

How to Use Django HttpResponseBadRequest

Page's source:

How to Use Django HttpResponseBadRequest



4. How to solve HttpResponseBadRequest is not defined

issue's output:

How to Use Django HttpResponseBadRequest

To solve this issue, you need to import the subclass before your view like:

from django.http import HttpResponseBadRequest