Skip to main content

Response Types

Since we are developing a website, the content of the response that you return from a view will usually be in HTML format. Based on what we have seen so far, you could simply create the HTML code inside a view and pass it to HttpResponse like this:

def index(request: HttpRequest) -> HttpResponse:
return HttpResponse("<html><strong>Hello</strong>, <em>world</em>!</html>")

Let's go one step further, and try to implement a view that creates an HTML table with course names and the number of enrolled students in each course. First create a SQLite database called myproject/courses.db (next to the manage.py file) with a courses table with some data like the following:

Courses Database

note

You can use the free DB Browser for SQLite to create and manage SQLite databases.

Then implement the courses() view in myapp/views.py, which queries the courses table and generates a bunch of HTML code:

import sqlite3

# ...remaining views...

def courses(request: HttpRequest) -> HttpResponse:
conn = sqlite3.connect("courses.db")
cursor = conn.cursor()
cursor.execute("SELECT name, enrolled_students FROM courses")
html="""
<html>
<title>Courses List</title>
<table style="border: 1px solid">
<thead>
<tr>
<th>Course</th>
<th>Students</th>
</tr>
</thead>
"""
for name, enrolled_students in cursor.fetchall():
html += f"""
<tr>
<td>{name}</td>
<td>{enrolled_students}</td>
</tr>
"""
html += "</table></html>"
conn.close()
return HttpResponse(html)

Finally bind this view with a URL in myapp/urls.py:

urlpatterns = [
path("", views.index, name="index"),
path("about-us", views.about_us, name="about_us"),
path("courses", views.courses, name="courses")
]

Now visit http://127.0.0.1:8000/myapp/courses and you will see:

View Rendering A List of Courses

You can also return responses in other formats, such as JSON or XML if you are developing a web service. Here, for example, is a view that returns this same table in JSON format:

from django.http import HttpRequest, HttpResponse, JsonResponse

# ... remaining views ...

def courses_json(request: HttpRequest) -> JsonResponse:
conn = sqlite3.connect("courses.db")
cursor = conn.cursor()
cursor.execute("SELECT name, enrolled_students FROM courses")
response = JsonResponse(cursor.fetchall(), safe=False)
conn.close()
return response

Note that the response class is now JsonResponse instead of HttpResponse.

Then set up the URL binding:

urlpatterns = [
path("", views.index, name="index"),
path("about-us", views.about_us, name="about_us"),
path("courses", views.courses, name="courses"),
path("courses/json", views.courses_json, name="courses_json")
]

If you visit http://127.0.0.1:8000/myapp/courses/json with Firefox you will see something like this:

View Rendering A List of Courses in JSON

Or in the interactive shell via Requests:

>>> import requests
>>> r = requests.get("http://127.0.0.1:8000/myapp/courses/json")
>>> r.json()
[['Python', 10], ['Java', 12], ['PHP', 8]]