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>')
urls.py
Now, let's add a path for the view.
path('http-response/', http_response),
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
Adding a path for ou view.
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
Submitting an empty username.
Result:
How to Use Django HttpResponse
Happy coding!
Top comments (0)