unicode.txt 17 KB

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