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.


views.py:

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


from django.http import HttpResponse

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


urls.py:

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


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


result:

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.


views.py:

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>')
        else:
            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.


urls.py:

our view's path


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


HttpResponse.html


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


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

</body>
</html>

now let's test the function.


submitting "mark" username

How to Use Django HttpResponse

result:

How to Use Django HttpResponse

submitting empty username

result:

How to Use Django HttpResponse