unicode.txt 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394
  1. ============
  2. Unicode data
  3. ============
  4. Django natively supports Unicode data everywhere. Providing your database can
  5. somehow store the data, you can safely pass around Unicode strings to
  6. templates, models and the database.
  7. This document tells you what you need to know if you're writing applications
  8. that use data or templates that are encoded in something other than ASCII.
  9. Creating the database
  10. =====================
  11. Make sure your database is configured to be able to store arbitrary string
  12. data. Normally, this means giving it an encoding of UTF-8 or UTF-16. If you use
  13. a more restrictive encoding -- for example, latin1 (iso8859-1) -- you won't be
  14. able to store certain characters in the database, and information will be lost.
  15. * MySQL users, refer to the `MySQL manual`_ (section 9.1.3.2 for MySQL 5.1)
  16. for details on how to set or alter the database character set encoding.
  17. * PostgreSQL users, refer to the `PostgreSQL manual`_ (section 22.3.2 in
  18. PostgreSQL 9) for details on creating databases with the correct encoding.
  19. * SQLite users, there is nothing you need to do. SQLite always uses UTF-8
  20. for internal encoding.
  21. .. _MySQL manual: http://dev.mysql.com/doc/refman/5.1/en/charset-database.html
  22. .. _PostgreSQL manual: http://www.postgresql.org/docs/current/static/multibyte.html
  23. All of Django's database backends automatically convert Unicode strings into
  24. the appropriate encoding for talking to the database. They also automatically
  25. convert strings retrieved from the database into Python Unicode strings. You
  26. don't even need to tell Django what encoding your database uses: that is
  27. handled transparently.
  28. For more, see the section "The database API" below.
  29. General string handling
  30. =======================
  31. Whenever you use strings with Django -- e.g., in database lookups, template
  32. rendering or anywhere else -- you have two choices for encoding those strings.
  33. You can use Unicode strings, or you can use normal strings (sometimes called
  34. "bytestrings") that are encoded using UTF-8.
  35. In Python 3, the logic is reversed, that is normal strings are Unicode, and
  36. when you want to specifically create a bytestring, you have to prefix the
  37. string with a 'b'. As we are doing in Django code from version 1.5,
  38. we recommend that you import ``unicode_literals`` from the __future__ library
  39. in your code. Then, when you specifically want to create a bytestring literal,
  40. prefix the string with 'b'.
  41. Python 2 legacy::
  42. my_string = "This is a bytestring"
  43. my_unicode = u"This is an Unicode string"
  44. Python 2 with unicode literals or Python 3::
  45. from __future__ import unicode_literals
  46. my_string = b"This is a bytestring"
  47. my_unicode = "This is an Unicode string"
  48. See also :doc:`Python 3 compatibility </topics/python3>`.
  49. .. warning::
  50. A bytestring does not carry any information with it about its encoding.
  51. For that reason, we have to make an assumption, and Django assumes that all
  52. bytestrings are in UTF-8.
  53. If you pass a string to Django that has been encoded in some other format,
  54. things will go wrong in interesting ways. Usually, Django will raise a
  55. ``UnicodeDecodeError`` at some point.
  56. If your code only uses ASCII data, it's safe to use your normal strings,
  57. passing them around at will, because ASCII is a subset of UTF-8.
  58. Don't be fooled into thinking that if your :setting:`DEFAULT_CHARSET` setting is set
  59. to something other than ``'utf-8'`` you can use that other encoding in your
  60. bytestrings! :setting:`DEFAULT_CHARSET` only applies to the strings generated as
  61. the result of template rendering (and email). Django will always assume UTF-8
  62. encoding for internal bytestrings. The reason for this is that the
  63. :setting:`DEFAULT_CHARSET` setting is not actually under your control (if you are the
  64. application developer). It's under the control of the person installing and
  65. using your application -- and if that person chooses a different setting, your
  66. code must still continue to work. Ergo, it cannot rely on that setting.
  67. In most cases when Django is dealing with strings, it will convert them to
  68. Unicode strings before doing anything else. So, as a general rule, if you pass
  69. in a bytestring, be prepared to receive a Unicode string back in the result.
  70. Translated strings
  71. ------------------
  72. Aside from Unicode strings and bytestrings, there's a third type of string-like
  73. object you may encounter when using Django. The framework's
  74. internationalization features introduce the concept of a "lazy translation" --
  75. a string that has been marked as translated but whose actual translation result
  76. isn't determined until the object is used in a string. This feature is useful
  77. in cases where the translation locale is unknown until the string is used, even
  78. though the string might have originally been created when the code was first
  79. imported.
  80. Normally, you won't have to worry about lazy translations. Just be aware that
  81. if you examine an object and it claims to be a
  82. ``django.utils.functional.__proxy__`` object, it is a lazy translation.
  83. Calling ``unicode()`` with the lazy translation as the argument will generate a
  84. Unicode string in the current locale.
  85. For more details about lazy translation objects, refer to the
  86. :doc:`internationalization </topics/i18n/index>` documentation.
  87. Useful utility functions
  88. ------------------------
  89. Because some string operations come up again and again, Django ships with a few
  90. useful functions that should make working with Unicode and bytestring objects
  91. a bit easier.
  92. Conversion functions
  93. ~~~~~~~~~~~~~~~~~~~~
  94. The ``django.utils.encoding`` module contains a few functions that are handy
  95. for converting back and forth between Unicode and bytestrings.
  96. * ``smart_text(s, encoding='utf-8', strings_only=False, errors='strict')``
  97. converts its input to a Unicode string. The ``encoding`` parameter
  98. specifies the input encoding. (For example, Django uses this internally
  99. when processing form input data, which might not be UTF-8 encoded.) The
  100. ``strings_only`` parameter, if set to True, will result in Python
  101. numbers, booleans and ``None`` not being converted to a string (they keep
  102. their original types). The ``errors`` parameter takes any of the values
  103. that are accepted by Python's ``unicode()`` function for its error
  104. handling.
  105. If you pass ``smart_text()`` an object that has a ``__unicode__``
  106. method, it will use that method to do the conversion.
  107. * ``force_text(s, encoding='utf-8', strings_only=False,
  108. errors='strict')`` is identical to ``smart_text()`` in almost all
  109. cases. The difference is when the first argument is a :ref:`lazy
  110. translation <lazy-translations>` instance. While ``smart_text()``
  111. preserves lazy translations, ``force_text()`` forces those objects to a
  112. Unicode string (causing the translation to occur). Normally, you'll want
  113. to use ``smart_text()``. However, ``force_text()`` is useful in
  114. template tags and filters that absolutely *must* have a string to work
  115. with, not just something that can be converted to a string.
  116. * ``smart_bytes(s, encoding='utf-8', strings_only=False, errors='strict')``
  117. is essentially the opposite of ``smart_text()``. It forces the first
  118. argument to a bytestring. The ``strings_only`` parameter has the same
  119. behavior as for ``smart_text()`` and ``force_text()``. This is
  120. slightly different semantics from Python's builtin ``str()`` function,
  121. but the difference is needed in a few places within Django's internals.
  122. Normally, you'll only need to use ``smart_text()``. Call it as early as
  123. possible on any input data that might be either Unicode or a bytestring, and
  124. from then on, you can treat the result as always being Unicode.
  125. .. _uri-and-iri-handling:
  126. URI and IRI handling
  127. ~~~~~~~~~~~~~~~~~~~~
  128. Web frameworks have to deal with URLs (which are a type of IRI_). One
  129. requirement of URLs is that they are encoded using only ASCII characters.
  130. However, in an international environment, you might need to construct a
  131. URL from an IRI_ -- very loosely speaking, a URI_ that can contain Unicode
  132. characters. Quoting and converting an IRI to URI can be a little tricky, so
  133. Django provides some assistance.
  134. * The function ``django.utils.encoding.iri_to_uri()`` implements the
  135. conversion from IRI to URI as required by the specification (:rfc:`3987`).
  136. * The functions ``django.utils.http.urlquote()`` and
  137. ``django.utils.http.urlquote_plus()`` are versions of Python's standard
  138. ``urllib.quote()`` and ``urllib.quote_plus()`` that work with non-ASCII
  139. characters. (The data is converted to UTF-8 prior to encoding.)
  140. These two groups of functions have slightly different purposes, and it's
  141. important to keep them straight. Normally, you would use ``urlquote()`` on the
  142. individual portions of the IRI or URI path so that any reserved characters
  143. such as '&' or '%' are correctly encoded. Then, you apply ``iri_to_uri()`` to
  144. the full IRI and it converts any non-ASCII characters to the correct encoded
  145. values.
  146. .. note::
  147. Technically, it isn't correct to say that ``iri_to_uri()`` implements the
  148. full algorithm in the IRI specification. It doesn't (yet) perform the
  149. international domain name encoding portion of the algorithm.
  150. The ``iri_to_uri()`` function will not change ASCII characters that are
  151. otherwise permitted in a URL. So, for example, the character '%' is not
  152. further encoded when passed to ``iri_to_uri()``. This means you can pass a
  153. full URL to this function and it will not mess up the query string or anything
  154. like that.
  155. An example might clarify things here::
  156. >>> urlquote('Paris & Orléans')
  157. 'Paris%20%26%20Orl%C3%A9ans'
  158. >>> iri_to_uri('/favorites/François/%s' % urlquote('Paris & Orléans'))
  159. '/favorites/Fran%C3%A7ois/Paris%20%26%20Orl%C3%A9ans'
  160. If you look carefully, you can see that the portion that was generated by
  161. ``urlquote()`` in the second example was not double-quoted when passed to
  162. ``iri_to_uri()``. This is a very important and useful feature. It means that
  163. you can construct your IRI without worrying about whether it contains
  164. non-ASCII characters and then, right at the end, call ``iri_to_uri()`` on the
  165. result.
  166. The ``iri_to_uri()`` function is also idempotent, which means the following is
  167. always true::
  168. iri_to_uri(iri_to_uri(some_string)) = iri_to_uri(some_string)
  169. So you can safely call it multiple times on the same IRI without risking
  170. double-quoting problems.
  171. .. _URI: http://www.ietf.org/rfc/rfc2396.txt
  172. .. _IRI: http://www.ietf.org/rfc/rfc3987.txt
  173. Models
  174. ======
  175. Because all strings are returned from the database as Unicode strings, model
  176. fields that are character based (CharField, TextField, URLField, etc) will
  177. contain Unicode values when Django retrieves data from the database. This
  178. is *always* the case, even if the data could fit into an ASCII bytestring.
  179. You can pass in bytestrings when creating a model or populating a field, and
  180. Django will convert it to Unicode when it needs to.
  181. Choosing between ``__str__()`` and ``__unicode__()``
  182. ----------------------------------------------------
  183. .. note::
  184. If you are on Python 3, you can skip this section because you'll always
  185. create ``__str__()`` rather than ``__unicode__()``. If you'd like
  186. compatibility with Python 2, you can decorate your model class with
  187. :func:`~django.utils.encoding.python_2_unicode_compatible`.
  188. One consequence of using Unicode by default is that you have to take some care
  189. when printing data from the model.
  190. In particular, rather than giving your model a ``__str__()`` method, we
  191. recommended you implement a ``__unicode__()`` method. In the ``__unicode__()``
  192. method, you can quite safely return the values of all your fields without
  193. having to worry about whether they fit into a bytestring or not. (The way
  194. Python works, the result of ``__str__()`` is *always* a bytestring, even if you
  195. accidentally try to return a Unicode object).
  196. You can still create a ``__str__()`` method on your models if you want, of
  197. course, but you shouldn't need to do this unless you have a good reason.
  198. Django's ``Model`` base class automatically provides a ``__str__()``
  199. implementation that calls ``__unicode__()`` and encodes the result into UTF-8.
  200. This means you'll normally only need to implement a ``__unicode__()`` method
  201. and let Django handle the coercion to a bytestring when required.
  202. Taking care in ``get_absolute_url()``
  203. -------------------------------------
  204. URLs can only contain ASCII characters. If you're constructing a URL from
  205. pieces of data that might be non-ASCII, be careful to encode the results in a
  206. way that is suitable for a URL. The :func:`~django.core.urlresolvers.reverse`
  207. function handles this for you automatically.
  208. If you're constructing a URL manually (i.e., *not* using the ``reverse()``
  209. function), you'll need to take care of the encoding yourself. In this case,
  210. use the ``iri_to_uri()`` and ``urlquote()`` functions that were documented
  211. above_. For example::
  212. from django.utils.encoding import iri_to_uri
  213. from django.utils.http import urlquote
  214. def get_absolute_url(self):
  215. url = '/person/%s/?x=0&y=0' % urlquote(self.location)
  216. return iri_to_uri(url)
  217. This function returns a correctly encoded URL even if ``self.location`` is
  218. something like "Jack visited Paris & Orléans". (In fact, the ``iri_to_uri()``
  219. call isn't strictly necessary in the above example, because all the
  220. non-ASCII characters would have been removed in quoting in the first line.)
  221. .. _above: `URI and IRI handling`_
  222. The database API
  223. ================
  224. You can pass either Unicode strings or UTF-8 bytestrings as arguments to
  225. ``filter()`` methods and the like in the database API. The following two
  226. querysets are identical::
  227. from __future__ import unicode_literals
  228. qs = People.objects.filter(name__contains='Å')
  229. qs = People.objects.filter(name__contains=b'\xc3\x85') # UTF-8 encoding of Å
  230. Templates
  231. =========
  232. You can use either Unicode or bytestrings when creating templates manually::
  233. from __future__ import unicode_literals
  234. from django.template import Template
  235. t1 = Template(b'This is a bytestring template.')
  236. t2 = Template('This is a Unicode template.')
  237. But the common case is to read templates from the filesystem, and this creates
  238. a slight complication: not all filesystems store their data encoded as UTF-8.
  239. If your template files are not stored with a UTF-8 encoding, set the :setting:`FILE_CHARSET`
  240. setting to the encoding of the files on disk. When Django reads in a template
  241. file, it will convert the data from this encoding to Unicode. (:setting:`FILE_CHARSET`
  242. is set to ``'utf-8'`` by default.)
  243. The :setting:`DEFAULT_CHARSET` setting controls the encoding of rendered templates.
  244. This is set to UTF-8 by default.
  245. Template tags and filters
  246. -------------------------
  247. A couple of tips to remember when writing your own template tags and filters:
  248. * Always return Unicode strings from a template tag's ``render()`` method
  249. and from template filters.
  250. * Use ``force_text()`` in preference to ``smart_text()`` in these
  251. places. Tag rendering and filter calls occur as the template is being
  252. rendered, so there is no advantage to postponing the conversion of lazy
  253. translation objects into strings. It's easier to work solely with Unicode
  254. strings at that point.
  255. Email
  256. =====
  257. Django's email framework (in ``django.core.mail``) supports Unicode
  258. transparently. You can use Unicode data in the message bodies and any headers.
  259. However, you're still obligated to respect the requirements of the email
  260. specifications, so, for example, email addresses should use only ASCII
  261. characters.
  262. The following code example demonstrates that everything except email addresses
  263. can be non-ASCII::
  264. from __future__ import unicode_literals
  265. from django.core.mail import EmailMessage
  266. subject = 'My visit to Sør-Trøndelag'
  267. sender = 'Arnbjörg Ráðormsdóttir <arnbjorg@example.com>'
  268. recipients = ['Fred <fred@example.com']
  269. body = '...'
  270. msg = EmailMessage(subject, body, sender, recipients)
  271. msg.attach("Une pièce jointe.pdf", "%PDF-1.4.%...", mimetype="application/pdf")
  272. msg.send()
  273. Form submission
  274. ===============
  275. HTML form submission is a tricky area. There's no guarantee that the
  276. submission will include encoding information, which means the framework might
  277. have to guess at the encoding of submitted data.
  278. Django adopts a "lazy" approach to decoding form data. The data in an
  279. ``HttpRequest`` object is only decoded when you access it. In fact, most of
  280. the data is not decoded at all. Only the ``HttpRequest.GET`` and
  281. ``HttpRequest.POST`` data structures have any decoding applied to them. Those
  282. two fields will return their members as Unicode data. All other attributes and
  283. methods of ``HttpRequest`` return data exactly as it was submitted by the
  284. client.
  285. By default, the :setting:`DEFAULT_CHARSET` setting is used as the assumed encoding
  286. for form data. If you need to change this for a particular form, you can set
  287. the ``encoding`` attribute on an ``HttpRequest`` instance. For example::
  288. def some_view(request):
  289. # We know that the data must be encoded as KOI8-R (for some reason).
  290. request.encoding = 'koi8-r'
  291. ...
  292. You can even change the encoding after having accessed ``request.GET`` or
  293. ``request.POST``, and all subsequent accesses will use the new encoding.
  294. Most developers won't need to worry about changing form encoding, but this is
  295. a useful feature for applications that talk to legacy systems whose encoding
  296. you cannot control.
  297. Django does not decode the data of file uploads, because that data is normally
  298. treated as collections of bytes, rather than strings. Any automatic decoding
  299. there would alter the meaning of the stream of bytes.