Making your code compatible with both Python 2.7 and Python 3

Since version 1.7, Django can be used with Python 2.7 and Python 3. In this recipe, we will take a look at the operations to make your code compatible with both the Python versions.

Getting ready

When creating a new Django project or upgrading an old existing project, consider following the rules given in this recipe.

How to do it…

Making your code compatible with both Python versions consists of the following steps:

  1. At the top of each module, add from __future__ import unicode_literals and then use usual quotes without a u prefix for Unicode strings and a b prefix for bytestrings.
  2. To ensure that a value is bytestring, use the django.utils.encoding.smart_bytes function. To ensure that a value ...

Get Django: Web Development with Python now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.