Last modified: Jan 10, 2023 By Alexander Williams

How to Use Django HttpResponse

HttpResponse is a class thats return an http response, and in ths tutorial, we'll learn how to use HttpResponse with simple examples.

1. HttpResponse

As we said, HttpResponse() returns an http response, so in this first example, we'll write a simple view that returns some HTML contents as response.

In our file, we need to add this view function.

from django.http import HttpResponse

def http_response(request):
    return HttpResponse('<h1>Hello HttpResponse</h1>')

now, let's add a path for the view.

path('http-response/', http_response), 


How to Use Django HttpResponse

2. HttpResponse with form

In this second example, we'll write a view that we'll use HttpResponse as a form response.

let's, see the example.

In our views, we need to this following view function.

def http_response_form(request):
    if request.method == "POST":
        username = request.POST.get('username')
        if username:
            return HttpResponse(f'<h1>hello {username}</h1>')
            return HttpResponse('<h1>please, enter your username</h1>')

    return render(request, "HttpResponse.html")

So, after submitting the form, if the username's input is not empty, the browser we'll return hello with the username, else the browser we'll return please, enter your username.

our view's path

path('http-response-form', http_response_form, name="httpresponse")


<!DOCTYPE html>
    <title>Test httpResponse with form</title>
<body style="padding-top: 20px">

    <form method="POST" action="{% url 'httpresponse' %}">
        {% csrf_token %}
        <input type="text" name="username">
        <input type="submit" name="submit">


now let's test the function.

submitting "mark" username

How to Use Django HttpResponse


How to Use Django HttpResponse

submitting empty username


How to Use Django HttpResponse