DEV Community


Understanding Django HttpResponse

saidpy profile image saidpy Updated on ・2 min read

HttpResponse() is a class that returns an HTTP response.
in this tutorial, we'll understand 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.

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>')    
Enter fullscreen mode Exit fullscreen mode

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

path('http-response/', http_response), 
Enter fullscreen mode Exit fullscreen mode

Alt Text

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")
Enter fullscreen mode Exit fullscreen mode

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.

Adding a path for ou view.

path('http-response-form', http_response_form, name="httpresponse")
Enter fullscreen mode Exit fullscreen mode


<!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">

Enter fullscreen mode Exit fullscreen mode

Now let's test the function.

Submitting "mark" username

Alt Text

Submitting an empty username.

Alt Text

Happy coding!

Django HttpResponse


Editor guide