DEV Community

loading...

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.

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

urls.py

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

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

Result:
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.

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")
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.

urls.py

Adding a path for ou view.

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

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

Now let's test the function.

Submitting "mark" username

Result:
Alt Text

Submitting an empty username.

Result:
Alt Text

Happy coding!

References:
Django HttpResponse

Discussion

pic
Editor guide