The basics: views and MIME-types

Recall from ealier chapter that a view function is simply a Python function that takes a Web request and returns a Web response. This response can be the HTML contents of a Web page, or a redirect, or a 404 error, or an XML document, or an image …or anything, really. More formally, a Django view function must:

  • Accept an HttpRequest instance as its first argument; and
  • Return an HttpResponse instance.

The key to returning non-HTML content from a view lies in the HttpResponse class, specifically the content_type argument. By default, Django sets content_type to “text/html”. You can however, set content_type to any of the official Internet media types (MIME types) managed by IANA.

By tweaking the MIME type, we can indicate to the browser that we’ve returned a response of a different format. For example, let’s look at a view that returns a PNG image. To keep things simple,
we’ll just read the file off the disk:

from django.http import HttpResponse

def my_image(request):
image_data = open(“/path/to/my/image.png”, “rb”).read()
return HttpResponse(image_data, content_type=”image/png”)

That’s it! If you replace the image path in the open() call with a path to a real image, you can use this very simple view to serve an image, and the browser will display it correctly.

The other important thing to keep in mind is that HttpResponse objects implement Python’s standard file-like object API. This means that you can use an HttpResponse instance in any place Python (or a third-party library) expects a file. For an example of how that works, let’s take a look at producing CSV with Django.

Back to Tutorial

Share this post
[social_warfare]
Default Servlet Reference
Generating Non-HTML Content

Get industry recognized certification – Contact us

keyboard_arrow_up