1.2.txt 46 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183
  1. ========================
  2. Django 1.2 release notes
  3. ========================
  4. *May 17, 2010.*
  5. Welcome to Django 1.2!
  6. Nearly a year in the making, Django 1.2 packs an impressive list of :ref:`new
  7. features <whats-new-1.2>` and lots of bug fixes. These release notes cover
  8. the new features, as well as important changes you'll want to be aware of when
  9. upgrading from Django 1.1 or older versions.
  10. Overview
  11. ========
  12. Django 1.2 introduces several large, important new features, including:
  13. * Support for :ref:`multiple database connections
  14. <support-for-multiple-databases>` in a single Django instance.
  15. * `Model validation`_ inspired by Django's form validation.
  16. * Vastly :ref:`improved protection against Cross-Site Request Forgery
  17. <improved-csrf-protection>` (CSRF).
  18. * A new :ref:`user "messages" framework <messages-framework>` with support for
  19. cookie- and session-based message for both anonymous and authenticated users.
  20. * Hooks for `object-level permissions`_, `permissions for anonymous users`_,
  21. and :ref:`more flexible username requirements
  22. <relaxed-requirements-for-usernames>`.
  23. * Customization of email sending via `email backends`_.
  24. * New :ref:`"smart" if template tag <new-in-1.2-smart-if>` which supports
  25. comparison operators.
  26. These are just the highlights; full details and a complete list of features
  27. :ref:`may be found below <whats-new-1.2>`.
  28. .. seealso::
  29. `Django Advent`_ covered the release of Django 1.2 with a series of
  30. articles and tutorials that cover some of the new features in depth.
  31. .. _django advent: https://github.com/djangoadvent/djangoadvent-articles
  32. Wherever possible these features have been introduced in a backwards-compatible
  33. manner per :doc:`our API stability policy </misc/api-stability>` policy.
  34. However, a handful of features *have* changed in ways that, for some users, will be
  35. backwards-incompatible. The big changes are:
  36. * Support for Python 2.3 has been dropped. See the full notes
  37. below.
  38. * The new CSRF protection framework is not backwards-compatible with
  39. the old system. Users of the old system will not be affected until
  40. the old system is removed in Django 1.4.
  41. However, upgrading to the new CSRF protection framework requires a few
  42. important backwards-incompatible changes, detailed in `CSRF Protection`_,
  43. below.
  44. * Authors of custom :class:`~django.db.models.Field` subclasses should be
  45. aware that a number of methods have had a change in prototype, detailed
  46. under `get_db_prep_*() methods on Field`_, below.
  47. * The internals of template tags have changed somewhat; authors of custom
  48. template tags that need to store state (e.g. custom control flow tags)
  49. should ensure that their code follows the new rules for `stateful template
  50. tags`_
  51. * The :func:`~django.contrib.auth.decorators.user_passes_test`,
  52. :func:`~django.contrib.auth.decorators.login_required`, and
  53. :func:`~django.contrib.auth.decorators.permission_required`, decorators
  54. from :mod:`django.contrib.auth` only apply to functions and no longer
  55. work on methods. There's a simple one-line fix :ref:`detailed below
  56. <user-passes-test-login-required-permission-required>`.
  57. Again, these are just the big features that will affect the most users. Users
  58. upgrading from previous versions of Django are heavily encouraged to consult
  59. the complete list of :ref:`backwards-incompatible changes
  60. <backwards-incompatible-changes-1.2>` and the list of :ref:`deprecated
  61. features <deprecated-features-1.2>`.
  62. Python compatibility
  63. ====================
  64. While not a new feature, it's important to note that Django 1.2
  65. introduces the first shift in our Python compatibility policy since
  66. Django's initial public debut. Previous Django releases were tested
  67. and supported on 2.x Python versions from 2.3 up; Django 1.2, however,
  68. drops official support for Python 2.3. As such, the minimum Python
  69. version required for Django is now 2.4, and Django is tested and
  70. supported on Python 2.4, 2.5 and 2.6, and will be supported on the
  71. as-yet-unreleased Python 2.7.
  72. This change should affect only a small number of Django users, as most
  73. operating-system vendors today are shipping Python 2.4 or newer as
  74. their default version. If you're still using Python 2.3, however,
  75. you'll need to stick to Django 1.1 until you can upgrade; per
  76. :doc:`our support policy </internals/release-process>`, Django 1.1 will
  77. continue to receive security support until the release of Django 1.3.
  78. A roadmap for Django's overall 2.x Python support, and eventual
  79. transition to Python 3.x, is currently being developed, and will be
  80. announced prior to the release of Django 1.3.
  81. .. _whats-new-1.2:
  82. What's new in Django 1.2
  83. ========================
  84. .. _support-for-multiple-databases:
  85. Support for multiple databases
  86. ------------------------------
  87. Django 1.2 adds the ability to use :doc:`more than one database
  88. </topics/db/multi-db>` in your Django project. Queries can be issued at a
  89. specific database with the ``using()`` method on ``QuerySet`` objects.
  90. Individual objects can be saved to a specific database by providing a ``using``
  91. argument when you call ``save()``.
  92. Model validation
  93. ----------------
  94. Model instances now have support for :ref:`validating their own data
  95. <validating-objects>`, and both model and form fields now accept configurable
  96. lists of :doc:`validators </ref/validators>` specifying reusable, encapsulated
  97. validation behavior. Note, however, that validation must still be performed
  98. explicitly. Simply invoking a model instance's ``save()`` method will not
  99. perform any validation of the instance's data.
  100. .. _improved-csrf-protection:
  101. Improved CSRF protection
  102. ------------------------
  103. Django now has much improved protection against :doc:`Cross-Site Request Forgery
  104. (CSRF) attacks</ref/csrf>`. This type of attack occurs when a malicious
  105. website contains a link, a form button or some JavaScript that is intended to
  106. perform some action on your website, using the credentials of a logged-in user
  107. who visits the malicious site in their browser. A related type of attack, "login
  108. CSRF," where an attacking site tricks a user's browser into logging into a site
  109. with someone else's credentials, is also covered.
  110. .. _messages-framework:
  111. Messages framework
  112. ------------------
  113. Django now includes a robust and configurable :doc:`messages framework
  114. </ref/contrib/messages>` with built-in support for cookie- and session-based
  115. messaging, for both anonymous and authenticated clients. The messages framework
  116. replaces the deprecated user message API and allows you to temporarily store
  117. messages in one request and retrieve them for display in a subsequent request
  118. (usually the next one).
  119. Object-level permissions
  120. ------------------------
  121. A foundation for specifying permissions at the per-object level has been added.
  122. Although there is no implementation of this in core, a custom authentication
  123. backend can provide this implementation and it will be used by
  124. :class:`django.contrib.auth.models.User`. See the :doc:`authentication docs
  125. </topics/auth/index>` for more information.
  126. Permissions for anonymous users
  127. -------------------------------
  128. If you provide a custom auth backend with ``supports_anonymous_user`` set to
  129. ``True``, AnonymousUser will check the backend for permissions, just like
  130. User already did. This is useful for centralizing permission handling - apps
  131. can always delegate the question of whether something is allowed or not to
  132. the authorization/authentication backend. See the :doc:`authentication
  133. docs </topics/auth/index>` for more details.
  134. .. _relaxed-requirements-for-usernames:
  135. Relaxed requirements for usernames
  136. ----------------------------------
  137. The built-in :class:`~django.contrib.auth.models.User` model's
  138. :attr:`~django.contrib.auth.models.User.username` field now allows a wider range
  139. of characters, including ``@``, ``+``, ``.`` and ``-`` characters.
  140. Email backends
  141. --------------
  142. You can now :ref:`configure the way that Django sends email
  143. <topic-email-backends>`. Instead of using SMTP to send all email, you
  144. can now choose a configurable email backend to send messages. If your
  145. hosting provider uses a sandbox or some other non-SMTP technique for
  146. sending mail, you can now construct an email backend that will allow
  147. Django's standard :doc:`mail sending methods</topics/email>` to use
  148. those facilities.
  149. This also makes it easier to debug mail sending. Django ships with
  150. backend implementations that allow you to send email to a
  151. :ref:`file<topic-email-file-backend>`, to the
  152. :ref:`console<topic-email-console-backend>`, or to
  153. :ref:`memory<topic-email-memory-backend>`. You can even configure all
  154. email to be :ref:`thrown away<topic-email-dummy-backend>`.
  155. .. _new-in-1.2-smart-if:
  156. "Smart" :ttag:`if` tag
  157. ----------------------
  158. The :ttag:`if` tag has been upgraded to be much more powerful. First, we've
  159. added support for comparison operators. No longer will you have to type:
  160. .. code-block:: html+django
  161. {% ifnotequal a b %}
  162. ...
  163. {% endifnotequal %}
  164. You can now do this:
  165. .. code-block:: html+django
  166. {% if a != b %}
  167. ...
  168. {% endif %}
  169. There's really no reason to use ``{% ifequal %}`` or ``{% ifnotequal %}``
  170. anymore, unless you're the nostalgic type.
  171. The operators supported are ``==``, ``!=``, ``<``, ``>``, ``<=``, ``>=``,
  172. ``in`` and ``not in``, all of which work like the Python operators, in addition
  173. to ``and``, ``or`` and ``not``, which were already supported.
  174. Also, filters may now be used in the ``if`` expression. For example:
  175. .. code-block:: html+django
  176. <div
  177. {% if user.email|lower == message.recipient|lower %}
  178. class="highlight"
  179. {% endif %}
  180. >{{ message }}</div>
  181. Template caching
  182. ----------------
  183. In previous versions of Django, every time you rendered a template, it
  184. would be reloaded from disk. In Django 1.2, you can use a :ref:`cached
  185. template loader <template-loaders>` to load templates once, then
  186. cache the result for every subsequent render. This can lead to a
  187. significant performance improvement if your templates are broken into
  188. lots of smaller subtemplates (using the ``{% extends %}`` or ``{%
  189. include %}`` tags).
  190. As a side effect, it is now much easier to support non-Django template
  191. languages.
  192. Class-based template loaders
  193. ----------------------------
  194. As part of the changes made to introduce `Template caching`_ and following
  195. a general trend in Django, the template loaders API has been modified
  196. to use template loading mechanisms that are encapsulated in Python classes as
  197. opposed to functions, the only method available until Django 1.1.
  198. All the template loaders :ref:`shipped with Django <template-loaders>` have
  199. been ported to the new API but they still implement the function-based API and
  200. the template core machinery still accepts function-based loaders (builtin or
  201. third party) so there is no immediate need to modify your ``TEMPLATE_LOADERS``
  202. setting in existing projects, things will keep working if you leave it
  203. untouched up to and including the Django 1.3 release.
  204. If you have developed your own custom template loaders we suggest to consider
  205. porting them to a class-based implementation because the code for backwards
  206. compatibility with function-based loaders starts its deprecation process in
  207. Django 1.2 and will be removed in Django 1.4. There is a description of the
  208. API these loader classes must implement in the template API reference and you
  209. can also examine the source code of the loaders shipped with Django.
  210. Natural keys in fixtures
  211. ------------------------
  212. Fixtures can now refer to remote objects using
  213. :ref:`topics-serialization-natural-keys`. This lookup scheme is an
  214. alternative to the normal primary-key based object references in a
  215. fixture, improving readability and resolving problems referring to
  216. objects whose primary key value may not be predictable or known.
  217. Fast failure for tests
  218. ----------------------
  219. Both the :djadmin:`test` subcommand of ``django-admin.py`` and the
  220. ``runtests.py`` script used to run Django's own test suite now support a
  221. ``--failfast`` option. When specified, this option causes the test runner to
  222. exit after encountering a failure instead of continuing with the test run. In
  223. addition, the handling of ``Ctrl-C`` during a test run has been improved to
  224. trigger a graceful exit from the test run that reports details of the tests that
  225. were run before the interruption.
  226. ``BigIntegerField``
  227. -------------------
  228. Models can now use a 64-bit :class:`~django.db.models.BigIntegerField` type.
  229. Improved localization
  230. ---------------------
  231. Django's :doc:`internationalization framework </topics/i18n/index>` has been expanded
  232. with locale-aware formatting and form processing. That means, if enabled, dates
  233. and numbers on templates will be displayed using the format specified for the
  234. current locale. Django will also use localized formats when parsing data in
  235. forms. See :doc:`/topics/i18n/formatting` for more details.
  236. ``readonly_fields`` in ``ModelAdmin``
  237. -------------------------------------
  238. :attr:`django.contrib.admin.ModelAdmin.readonly_fields` has been added to
  239. enable non-editable fields in add/change pages for models and inlines. Field
  240. and calculated values can be displayed alongside editable fields.
  241. Customizable syntax highlighting
  242. --------------------------------
  243. You can now use a :envvar:`DJANGO_COLORS` environment variable to modify or
  244. disable the colors used by ``django-admin.py`` to provide :ref:`syntax
  245. highlighting <syntax-coloring>`.
  246. Syndication feeds as views
  247. --------------------------
  248. :doc:`Syndication feeds </ref/contrib/syndication>` can now be used directly as
  249. views in your :doc:`URLconf </topics/http/urls>`. This means that you can
  250. maintain complete control over the URL structure of your feeds. Like any other
  251. view, feeds views are passed a ``request`` object, so you can do anything you
  252. would normally do with a view, like user based access control, or making a feed
  253. a named URL.
  254. GeoDjango
  255. ---------
  256. The most significant new feature for :doc:`GeoDjango </ref/contrib/gis/index>`
  257. in 1.2 is support for multiple spatial databases. As a result,
  258. the following :ref:`spatial database backends <spatial-backends>`
  259. are now included:
  260. * ``django.contrib.gis.db.backends.postgis``
  261. * ``django.contrib.gis.db.backends.mysql``
  262. * ``django.contrib.gis.db.backends.oracle``
  263. * ``django.contrib.gis.db.backends.spatialite``
  264. GeoDjango now supports the rich capabilities added in the PostGIS 1.5 release.
  265. New features include support for the :ref:`geography type <geography-type>`
  266. and enabling of :ref:`distance queries <distance-queries>`
  267. with non-point geometries on geographic coordinate systems.
  268. Support for 3D geometry fields was added, and may be enabled
  269. by setting the :attr:`~django.contrib.gis.db.models.GeometryField.dim`
  270. keyword to 3 in your :class:`~django.contrib.gis.db.models.GeometryField`.
  271. The :class:`~django.contrib.gis.db.models.Extent3D` aggregate
  272. and ``extent3d()`` ``GeoQuerySet`` method were added as a part of this feature.
  273. The ``force_rhr()``, ``reverse_geom()``, and ``geohash()`` ``GeoQuerySet``
  274. methods are new.
  275. The GEOS interface was updated to use thread-safe C library functions when
  276. available on the platform.
  277. The GDAL interface now allows the user to set a
  278. :attr:`~django.contrib.gis.gdal.Layer.spatial_filter` on the features returned
  279. when iterating over a :class:`~django.contrib.gis.gdal.Layer`.
  280. Finally, :doc:`GeoDjango's documentation </ref/contrib/gis/index>` is now
  281. included with Django's and is no longer hosted separately at ``geodjango.org``.
  282. .. _1.2-js-assisted-inlines:
  283. JavaScript-assisted handling of inline related objects in the admin
  284. -------------------------------------------------------------------
  285. If a user has JavaScript enabled in their browser, the interface for
  286. inline objects in the admin now allows inline objects to be
  287. dynamically added and removed. Users without JavaScript-enabled
  288. browsers will see no change in the behavior of inline objects.
  289. New ``now`` template tag format specifier characters: ``c`` and ``u``
  290. ---------------------------------------------------------------------
  291. The argument to the :ttag:`now` has gained two new format characters:
  292. ``c`` to specify that a datetime value should be formatted in ISO 8601
  293. format, and ``u`` that allows output of the microseconds part of a
  294. datetime or time value.
  295. These are also available in others parts like the :tfilter:`date` and
  296. :tfilter:`time` template filters, the ``humanize`` template tag library
  297. and the new `format localization`_ framework.
  298. .. _format localization: `Improved localization`_
  299. .. _backwards-incompatible-changes-1.2:
  300. Backwards-incompatible changes in 1.2
  301. =====================================
  302. Wherever possible the new features above have been introduced in a
  303. backwards-compatible manner per :doc:`our API stability policy
  304. </misc/api-stability>` policy. This means that practically all existing
  305. code which worked with Django 1.1 will continue to work with Django
  306. 1.2; such code will, however, begin issuing warnings (see below for
  307. details).
  308. However, a handful of features *have* changed in ways that, for some
  309. users, will be immediately backwards-incompatible. Those changes are
  310. detailed below.
  311. CSRF Protection
  312. ---------------
  313. We've made large changes to the way CSRF protection works, detailed in
  314. :doc:`the CSRF documentation </ref/csrf>`. Here are the major changes you
  315. should be aware of:
  316. * ``CsrfResponseMiddleware`` and ``CsrfMiddleware`` have been deprecated and
  317. will be removed completely in Django 1.4, in favor of a template tag that
  318. should be inserted into forms.
  319. * All contrib apps use a ``csrf_protect`` decorator to protect the view. This
  320. requires the use of the ``csrf_token`` template tag in the template. If you
  321. have used custom templates for contrib views, you MUST READ THE UPGRADE
  322. INSTRUCTIONS to fix those templates.
  323. .. admonition:: Documentation removed
  324. The upgrade notes have been removed in current Django docs. Please refer
  325. to the docs for Django 1.3 or older to find these instructions.
  326. * ``CsrfViewMiddleware`` is included in ``MIDDLEWARE_CLASSES`` by
  327. default. This turns on CSRF protection by default, so views that accept
  328. POST requests need to be written to work with the middleware. Instructions
  329. on how to do this are found in the CSRF docs.
  330. * All of the CSRF has moved from contrib to core (with backwards
  331. compatible imports in the old locations, which are deprecated and
  332. will cease to be supported in Django 1.4).
  333. ``get_db_prep_*()`` methods on ``Field``
  334. ----------------------------------------
  335. Prior to Django 1.2, a custom ``Field`` had the option of defining
  336. several functions to support conversion of Python values into
  337. database-compatible values. A custom field might look something like::
  338. class CustomModelField(models.Field):
  339. ...
  340. def db_type(self):
  341. ...
  342. def get_db_prep_save(self, value):
  343. ...
  344. def get_db_prep_value(self, value):
  345. ...
  346. def get_db_prep_lookup(self, lookup_type, value):
  347. ...
  348. In 1.2, these three methods have undergone a change in prototype, and
  349. two extra methods have been introduced::
  350. class CustomModelField(models.Field):
  351. ...
  352. def db_type(self, connection):
  353. ...
  354. def get_prep_value(self, value):
  355. ...
  356. def get_prep_lookup(self, lookup_type, value):
  357. ...
  358. def get_db_prep_save(self, value, connection):
  359. ...
  360. def get_db_prep_value(self, value, connection, prepared=False):
  361. ...
  362. def get_db_prep_lookup(self, lookup_type, value, connection, prepared=False):
  363. ...
  364. These changes are required to support multiple databases --
  365. ``db_type`` and ``get_db_prep_*`` can no longer make any assumptions
  366. regarding the database for which it is preparing. The ``connection``
  367. argument now provides the preparation methods with the specific
  368. connection for which the value is being prepared.
  369. The two new methods exist to differentiate general data-preparation
  370. requirements from requirements that are database-specific. The
  371. ``prepared`` argument is used to indicate to the database-preparation
  372. methods whether generic value preparation has been performed. If
  373. an unprepared (i.e., ``prepared=False``) value is provided to the
  374. ``get_db_prep_*()`` calls, they should invoke the corresponding
  375. ``get_prep_*()`` calls to perform generic data preparation.
  376. We've provided conversion functions that will transparently
  377. convert functions adhering to the old prototype into functions
  378. compatible with the new prototype. However, these conversion functions
  379. will be removed in Django 1.4, so you should upgrade your ``Field``
  380. definitions to use the new prototype as soon as possible.
  381. If your ``get_db_prep_*()`` methods made no use of the database
  382. connection, you should be able to upgrade by renaming
  383. ``get_db_prep_value()`` to ``get_prep_value()`` and
  384. ``get_db_prep_lookup()`` to ``get_prep_lookup()``. If you require
  385. database specific conversions, then you will need to provide an
  386. implementation ``get_db_prep_*`` that uses the ``connection``
  387. argument to resolve database-specific values.
  388. Stateful template tags
  389. ----------------------
  390. Template tags that store rendering state on their ``Node`` subclass
  391. have always been vulnerable to thread-safety and other issues; as of
  392. Django 1.2, however, they may also cause problems when used with the
  393. new :ref:`cached template loader<template-loaders>`.
  394. All of the built-in Django template tags are safe to use with the cached
  395. loader, but if you're using custom template tags that come from third
  396. party packages, or from your own code, you should ensure that the
  397. ``Node`` implementation for each tag is thread-safe. For more
  398. information, see
  399. :ref:`template tag thread safety considerations<template_tag_thread_safety>`.
  400. You may also need to update your templates if you were relying on the
  401. implementation of Django's template tags *not* being thread safe. The
  402. :ttag:`cycle` tag is the most likely to be affected in this way,
  403. especially when used in conjunction with the :ttag:`include` tag.
  404. Consider the following template fragment:
  405. .. code-block:: html+django
  406. {% for object in object_list %}
  407. {% include "subtemplate.html" %}
  408. {% endfor %}
  409. with a ``subtemplate.html`` that reads:
  410. .. code-block:: html+django
  411. {% cycle 'even' 'odd' %}
  412. Using the non-thread-safe, pre-Django 1.2 renderer, this would output:
  413. .. code-block:: text
  414. even odd even odd ...
  415. Using the thread-safe Django 1.2 renderer, you will instead get:
  416. .. code-block:: text
  417. even even even even ...
  418. This is because each rendering of the :ttag:`include` tag is an
  419. independent rendering. When the :ttag:`cycle` tag was not thread safe,
  420. the state of the :ttag:`cycle` tag would leak between multiple
  421. renderings of the same :ttag:`include`. Now that the :ttag:`cycle` tag
  422. is thread safe, this leakage no longer occurs.
  423. .. _user-passes-test-login-required-permission-required:
  424. ``user_passes_test``, ``login_required`` and ``permission_required``
  425. --------------------------------------------------------------------
  426. ``django.contrib.auth.decorators`` provides the decorators
  427. ``login_required``, ``permission_required`` and
  428. ``user_passes_test``. Previously it was possible to use these
  429. decorators both on functions (where the first argument is 'request')
  430. and on methods (where the first argument is 'self', and the second
  431. argument is 'request'). Unfortunately, flaws were discovered in the
  432. code supporting this: it only works in limited circumstances, and
  433. produces errors that are very difficult to debug when it does not
  434. work.
  435. For this reason, the 'auto adapt' behavior has been removed, and if
  436. you are using these decorators on methods, you will need to manually
  437. apply :func:`django.utils.decorators.method_decorator` to convert the
  438. decorator to one that works with methods. For example, you would
  439. change code from this::
  440. class MyClass(object):
  441. @login_required
  442. def my_view(self, request):
  443. pass
  444. to this::
  445. from django.utils.decorators import method_decorator
  446. class MyClass(object):
  447. @method_decorator(login_required)
  448. def my_view(self, request):
  449. pass
  450. or::
  451. from django.utils.decorators import method_decorator
  452. login_required_m = method_decorator(login_required)
  453. class MyClass(object):
  454. @login_required_m
  455. def my_view(self, request):
  456. pass
  457. For those of you who've been following the development trunk, this
  458. change also applies to other decorators introduced since 1.1,
  459. including ``csrf_protect``, ``cache_control`` and anything created
  460. using ``decorator_from_middleware``.
  461. :ttag:`if` tag changes
  462. ----------------------
  463. Due to new features in the :ttag:`if` template tag, it no longer
  464. accepts 'and', 'or' and 'not' as valid **variable** names. Previously,
  465. these strings could be used as variable names. Now, the keyword status
  466. is always enforced, and template code such as ``{% if not %}`` or ``{%
  467. if and %}`` will throw a ``TemplateSyntaxError``. Also, ``in`` is a
  468. new keyword and so is not a valid variable name in this tag.
  469. ``LazyObject``
  470. --------------
  471. ``LazyObject`` is an undocumented-but-often-used utility class used for lazily
  472. wrapping other objects of unknown type.
  473. In Django 1.1 and earlier, it handled introspection in a non-standard way,
  474. depending on wrapped objects implementing a public method named
  475. ``get_all_members()``. Since this could easily lead to name clashes, it has been
  476. changed to use the standard Python introspection method, involving
  477. ``__members__`` and ``__dir__()``.
  478. If you used ``LazyObject`` in your own code
  479. and implemented the ``get_all_members()`` method for wrapped objects, you'll need
  480. to make a couple of changes:
  481. First, if your class does not have special requirements for introspection (i.e.,
  482. you have not implemented ``__getattr__()`` or other methods that allow for
  483. attributes not discoverable by normal mechanisms), you can simply remove the
  484. ``get_all_members()`` method. The default implementation on ``LazyObject`` will
  485. do the right thing.
  486. If you have more complex requirements for introspection, first rename the
  487. ``get_all_members()`` method to ``__dir__()``. This is the standard
  488. introspection method for Python 2.6 and above. If you require support for Python
  489. versions earlier than 2.6, add the following code to the class::
  490. __members__ = property(lambda self: self.__dir__())
  491. ``__dict__`` on model instances
  492. -------------------------------
  493. Historically, the ``__dict__`` attribute of a model instance has only contained
  494. attributes corresponding to the fields on a model.
  495. In order to support multiple database configurations, Django 1.2 has
  496. added a ``_state`` attribute to object instances. This attribute will
  497. appear in ``__dict__`` for a model instance. If your code relies on
  498. iterating over ``__dict__`` to obtain a list of fields, you must now
  499. be prepared to handle or filter out the ``_state`` attribute.
  500. Test runner exit status code
  501. ----------------------------
  502. The exit status code of the test runners (``tests/runtests.py`` and ``python
  503. manage.py test``) no longer represents the number of failed tests, because a
  504. failure of 256 or more tests resulted in a wrong exit status code. The exit
  505. status code for the test runner is now 0 for success (no failing tests) and 1
  506. for any number of test failures. If needed, the number of test failures can be
  507. found at the end of the test runner's output.
  508. Cookie encoding
  509. ---------------
  510. To fix bugs with cookies in Internet Explorer, Safari, and possibly
  511. other browsers, our encoding of cookie values was changed so that the
  512. comma and semicolon are treated as non-safe characters, and are
  513. therefore encoded as ``\054`` and ``\073`` respectively. This could
  514. produce backwards incompatibilities, especially if you are storing
  515. comma or semi-colon in cookies and have JavaScript code that parses
  516. and manipulates cookie values client-side.
  517. ``ModelForm.is_valid()`` and ``ModelForm.errors``
  518. -------------------------------------------------
  519. Much of the validation work for ModelForms has been moved down to the model
  520. level. As a result, the first time you call ``ModelForm.is_valid()``, access
  521. ``ModelForm.errors`` or otherwise trigger form validation, your model will be
  522. cleaned in-place. This conversion used to happen when the model was saved. If
  523. you need an unmodified instance of your model, you should pass a copy to the
  524. ``ModelForm`` constructor.
  525. ``BooleanField`` on MySQL
  526. --------------------------
  527. In previous versions of Django, a model's ``BooleanField`` under MySQL
  528. would return its value as either ``1`` or ``0``, instead of ``True``
  529. or ``False``; for most people this wasn't a problem because ``bool``
  530. is a subclass of ``int`` in Python. In Django 1.2, however,
  531. ``BooleanField`` on MySQL correctly returns a real ``bool``. The only
  532. time this should ever be an issue is if you were expecting the
  533. ``repr`` of a ``BooleanField`` to print ``1`` or ``0``.
  534. Changes to the interpretation of ``max_num`` in FormSets
  535. --------------------------------------------------------
  536. As part of enhancements made to the handling of FormSets, the default
  537. value and interpretation of the ``max_num`` parameter to the
  538. :ref:`django.forms.formsets.formset_factory() <formsets-max-num>` and
  539. :ref:`django.forms.models.modelformset_factory()
  540. <model-formsets-max-num>` functions has changed slightly. This
  541. change also affects the way the
  542. :attr:`~django.contrib.admin.InlineModelAdmin.max_num` argument is used for
  543. inline admin objects.
  544. Previously, the default value for ``max_num`` was ``0`` (zero).
  545. FormSets then used the boolean value of ``max_num`` to determine if a
  546. limit was to be imposed on the number of generated forms. The default
  547. value of ``0`` meant that there was no default limit on the number of
  548. forms in a FormSet.
  549. Starting with 1.2, the default value for ``max_num`` has been changed
  550. to ``None``, and FormSets will differentiate between a value of
  551. ``None`` and a value of ``0``. A value of ``None`` indicates that no
  552. limit on the number of forms is to be imposed; a value of ``0``
  553. indicates that a maximum of 0 forms should be imposed. This doesn't
  554. necessarily mean that no forms will be displayed -- see the
  555. :ref:`ModelFormSet documentation <model-formsets-max-num>` for more
  556. details.
  557. If you were manually specifying a value of ``0`` for ``max_num``, you
  558. will need to update your FormSet and/or admin definitions.
  559. .. seealso::
  560. :ref:`1.2-js-assisted-inlines`
  561. ``email_re``
  562. ------------
  563. An undocumented regular expression for validating email addresses has been moved
  564. from ``django.form.fields`` to ``django.core.validators``. You will need to
  565. update your imports if you are using it.
  566. .. _deprecated-features-1.2:
  567. Features deprecated in 1.2
  568. ==========================
  569. Finally, Django 1.2 deprecates some features from earlier releases.
  570. These features are still supported, but will be gradually phased out
  571. over the next few release cycles.
  572. Code taking advantage of any of the features below will raise a
  573. ``PendingDeprecationWarning`` in Django 1.2. This warning will be
  574. silent by default, but may be turned on using Python's :mod:`warnings`
  575. module, or by running Python with a ``-Wd`` or ``-Wall`` flag.
  576. In Django 1.3, these warnings will become a ``DeprecationWarning``,
  577. which is *not* silent. In Django 1.4 support for these features will
  578. be removed entirely.
  579. .. seealso::
  580. For more details, see the documentation :doc:`Django's release process
  581. </internals/release-process>` and our :doc:`deprecation timeline
  582. </internals/deprecation>`.`
  583. .. _specifying-databases:
  584. Specifying databases
  585. --------------------
  586. Prior to Django 1.2, Django used a number of settings to control
  587. access to a single database. Django 1.2 introduces support for
  588. multiple databases, and as a result the way you define database
  589. settings has changed.
  590. Any existing Django settings file will continue to work as expected
  591. until Django 1.4. Until then, old-style database settings will be
  592. automatically translated to the new-style format.
  593. In the old-style (pre 1.2) format, you had a number of ``DATABASE_``
  594. settings in your settings file. For example::
  595. DATABASE_NAME = 'test_db'
  596. DATABASE_ENGINE = 'postgresql_psycopg2'
  597. DATABASE_USER = 'myusername'
  598. DATABASE_PASSWORD = 's3krit'
  599. These settings are now in a dictionary named
  600. :setting:`DATABASES`. Each item in the dictionary corresponds to a
  601. single database connection, with the name ``'default'`` describing the
  602. default database connection. The setting names have also been
  603. shortened. The previous sample settings would now look like this::
  604. DATABASES = {
  605. 'default': {
  606. 'NAME': 'test_db',
  607. 'ENGINE': 'django.db.backends.postgresql_psycopg2',
  608. 'USER': 'myusername',
  609. 'PASSWORD': 's3krit',
  610. }
  611. }
  612. This affects the following settings:
  613. ========================================= ==========================
  614. Old setting New Setting
  615. ========================================= ==========================
  616. ``DATABASE_ENGINE`` :setting:`ENGINE <DATABASE-ENGINE>`
  617. ``DATABASE_HOST`` :setting:`HOST`
  618. ``DATABASE_NAME`` :setting:`NAME`
  619. ``DATABASE_OPTIONS`` :setting:`OPTIONS`
  620. ``DATABASE_PASSWORD`` :setting:`PASSWORD`
  621. ``DATABASE_PORT`` :setting:`PORT`
  622. ``DATABASE_USER`` :setting:`USER`
  623. ``TEST_DATABASE_CHARSET`` :setting:`TEST_CHARSET`
  624. ``TEST_DATABASE_COLLATION`` :setting:`TEST_COLLATION`
  625. ``TEST_DATABASE_NAME`` :setting:`TEST_NAME`
  626. ========================================= ==========================
  627. These changes are also required if you have manually created a database
  628. connection using ``DatabaseWrapper()`` from your database backend of choice.
  629. In addition to the change in structure, Django 1.2 removes the special
  630. handling for the built-in database backends. All database backends
  631. must now be specified by a fully qualified module name (i.e.,
  632. ``django.db.backends.postgresql_psycopg2``, rather than just
  633. ``postgresql_psycopg2``).
  634. ``postgresql`` database backend
  635. -------------------------------
  636. The ``psycopg1`` library has not been updated since October 2005. As a
  637. result, the ``postgresql`` database backend, which uses this library,
  638. has been deprecated.
  639. If you are currently using the ``postgresql`` backend, you should
  640. migrate to using the ``postgresql_psycopg2`` backend. To update your
  641. code, install the ``psycopg2`` library and change the
  642. :setting:`ENGINE <DATABASE-ENGINE>` setting to use
  643. ``django.db.backends.postgresql_psycopg2``.
  644. CSRF response-rewriting middleware
  645. ----------------------------------
  646. ``CsrfResponseMiddleware``, the middleware that automatically inserted
  647. CSRF tokens into ``POST`` forms in outgoing pages, has been deprecated
  648. in favor of a template tag method (see above), and will be removed
  649. completely in Django 1.4. ``CsrfMiddleware``, which includes the
  650. functionality of ``CsrfResponseMiddleware`` and
  651. ``CsrfViewMiddleware``, has likewise been deprecated.
  652. Also, the CSRF module has moved from contrib to core, and the old
  653. imports are deprecated, as described in the upgrading notes.
  654. .. admonition:: Documentation removed
  655. The upgrade notes have been removed in current Django docs. Please refer
  656. to the docs for Django 1.3 or older to find these instructions.
  657. ``SMTPConnection``
  658. ------------------
  659. The ``SMTPConnection`` class has been deprecated in favor of a generic
  660. email backend API. Old code that explicitly instantiated an instance
  661. of an SMTPConnection::
  662. from django.core.mail import SMTPConnection
  663. connection = SMTPConnection()
  664. messages = get_notification_email()
  665. connection.send_messages(messages)
  666. ...should now call :meth:`~django.core.mail.get_connection()` to
  667. instantiate a generic email connection::
  668. from django.core.mail import get_connection
  669. connection = get_connection()
  670. messages = get_notification_email()
  671. connection.send_messages(messages)
  672. Depending on the value of the :setting:`EMAIL_BACKEND` setting, this
  673. may not return an SMTP connection. If you explicitly require an SMTP
  674. connection with which to send email, you can explicitly request an
  675. SMTP connection::
  676. from django.core.mail import get_connection
  677. connection = get_connection('django.core.mail.backends.smtp.EmailBackend')
  678. messages = get_notification_email()
  679. connection.send_messages(messages)
  680. If your call to construct an instance of ``SMTPConnection`` required
  681. additional arguments, those arguments can be passed to the
  682. :meth:`~django.core.mail.get_connection()` call::
  683. connection = get_connection('django.core.mail.backends.smtp.EmailBackend', hostname='localhost', port=1234)
  684. User Messages API
  685. -----------------
  686. The API for storing messages in the user ``Message`` model (via
  687. ``user.message_set.create``) is now deprecated and will be removed in Django
  688. 1.4 according to the standard :doc:`release process </internals/release-process>`.
  689. To upgrade your code, you need to replace any instances of this::
  690. user.message_set.create('a message')
  691. ...with the following::
  692. from django.contrib import messages
  693. messages.add_message(request, messages.INFO, 'a message')
  694. Additionally, if you make use of the method, you need to replace the
  695. following::
  696. for message in user.get_and_delete_messages():
  697. ...
  698. ...with::
  699. from django.contrib import messages
  700. for message in messages.get_messages(request):
  701. ...
  702. For more information, see the full
  703. :doc:`messages documentation </ref/contrib/messages>`. You should begin to
  704. update your code to use the new API immediately.
  705. Date format helper functions
  706. ----------------------------
  707. ``django.utils.translation.get_date_formats()`` and
  708. ``django.utils.translation.get_partial_date_formats()`` have been deprecated
  709. in favor of the appropriate calls to ``django.utils.formats.get_format()``,
  710. which is locale-aware when ``USE_L10N`` is set to ``True``, and falls
  711. back to default settings if set to ``False``.
  712. To get the different date formats, instead of writing this::
  713. from django.utils.translation import get_date_formats
  714. date_format, datetime_format, time_format = get_date_formats()
  715. ...use::
  716. from django.utils import formats
  717. date_format = formats.get_format('DATE_FORMAT')
  718. datetime_format = formats.get_format('DATETIME_FORMAT')
  719. time_format = formats.get_format('TIME_FORMAT')
  720. Or, when directly formatting a date value::
  721. from django.utils import formats
  722. value_formatted = formats.date_format(value, 'DATETIME_FORMAT')
  723. The same applies to the globals found in ``django.forms.fields``:
  724. * ``DEFAULT_DATE_INPUT_FORMATS``
  725. * ``DEFAULT_TIME_INPUT_FORMATS``
  726. * ``DEFAULT_DATETIME_INPUT_FORMATS``
  727. Use ``django.utils.formats.get_format()`` to get the appropriate formats.
  728. Function-based test runners
  729. ---------------------------
  730. Django 1.2 changes the test runner tools to use a class-based
  731. approach. Old style function-based test runners will still work, but
  732. should be updated to use the new :ref:`class-based runners
  733. <topics-testing-test_runner>`.
  734. .. _1.2-updating-feeds:
  735. ``Feed`` in ``django.contrib.syndication.feeds``
  736. ------------------------------------------------
  737. The ``django.contrib.syndication.feeds.Feed`` class has been
  738. replaced by the :class:`django.contrib.syndication.views.Feed` class.
  739. The old ``feeds.Feed`` class is deprecated, and will be removed in
  740. Django 1.4.
  741. The new class has an almost identical API, but allows instances to be
  742. used as views. For example, consider the use of the old framework in
  743. the following :doc:`URLconf </topics/http/urls>`::
  744. from django.conf.urls.defaults import *
  745. from myproject.feeds import LatestEntries, LatestEntriesByCategory
  746. feeds = {
  747. 'latest': LatestEntries,
  748. 'categories': LatestEntriesByCategory,
  749. }
  750. urlpatterns = patterns('',
  751. # ...
  752. (r'^feeds/(?P<url>.*)/$', 'django.contrib.syndication.views.feed',
  753. {'feed_dict': feeds}),
  754. # ...
  755. )
  756. Using the new Feed class, these feeds can be deployed directly as views::
  757. from django.conf.urls.defaults import *
  758. from myproject.feeds import LatestEntries, LatestEntriesByCategory
  759. urlpatterns = patterns('',
  760. # ...
  761. (r'^feeds/latest/$', LatestEntries()),
  762. (r'^feeds/categories/(?P<category_id>\d+)/$', LatestEntriesByCategory()),
  763. # ...
  764. )
  765. If you currently use the ``feed()`` view, the ``LatestEntries`` class would
  766. often not need to be modified apart from subclassing the new
  767. :class:`~django.contrib.syndication.views.Feed` class. The exception is if
  768. Django was automatically working out the name of the template to use to render
  769. the feed's description and title elements (if you were not specifying the
  770. ``title_template`` and ``description_template`` attributes). You should ensure
  771. that you always specify ``title_template`` and ``description_template``
  772. attributes, or provide ``item_title()`` and ``item_description()`` methods.
  773. However, ``LatestEntriesByCategory`` uses the ``get_object()`` method
  774. with the ``bits`` argument to specify a specific category to show. In
  775. the new :class:`~django.contrib.syndication.views.Feed` class,
  776. ``get_object()`` method takes a ``request`` and arguments from the
  777. URL, so it would look like this::
  778. from django.contrib.syndication.views import Feed
  779. from django.shortcuts import get_object_or_404
  780. from myproject.models import Category
  781. class LatestEntriesByCategory(Feed):
  782. def get_object(self, request, category_id):
  783. return get_object_or_404(Category, id=category_id)
  784. # ...
  785. Additionally, the ``get_feed()`` method on ``Feed`` classes now take
  786. different arguments, which may impact you if you use the ``Feed``
  787. classes directly. Instead of just taking an optional ``url`` argument,
  788. it now takes two arguments: the object returned by its own
  789. ``get_object()`` method, and the current ``request`` object.
  790. To take into account ``Feed`` classes not being initialized for each
  791. request, the ``__init__()`` method now takes no arguments by default.
  792. Previously it would have taken the ``slug`` from the URL and the
  793. ``request`` object.
  794. In accordance with `RSS best practices`_, RSS feeds will now include
  795. an ``atom:link`` element. You may need to update your tests to take
  796. this into account.
  797. For more information, see the full :doc:`syndication framework
  798. documentation </ref/contrib/syndication>`.
  799. .. _RSS best practices: https://www.rssboard.org/rss-profile
  800. Technical message IDs
  801. ---------------------
  802. Up to version 1.1 Django used technical message IDs
  803. to provide localizers the possibility to translate date and time formats. They
  804. were translatable :term:`translation strings <translation string>` that could
  805. be recognized because they were all upper case (for example
  806. :setting:`DATETIME_FORMAT`, :setting:`DATE_FORMAT`, :setting:`TIME_FORMAT`).
  807. They have been deprecated in favor of the new :doc:`/topics/i18n/formatting`
  808. infrastructure that allows localizers to specify that information in a
  809. ``formats.py`` file in the corresponding ``django/conf/locale/<locale name>/``
  810. directory.
  811. GeoDjango
  812. ---------
  813. To allow support for multiple databases, the GeoDjango database internals were
  814. changed substantially. The largest backwards-incompatible change is that
  815. the module ``django.contrib.gis.db.backend`` was renamed to
  816. :mod:`django.contrib.gis.db.backends`, where the full-fledged
  817. :ref:`spatial database backends <spatial-backends>` now exist. The
  818. following sections provide information on the most-popular APIs that
  819. were affected by these changes.
  820. ``SpatialBackend``
  821. ~~~~~~~~~~~~~~~~~~
  822. Prior to the creation of the separate spatial backends, the
  823. ``django.contrib.gis.db.backend.SpatialBackend`` object was
  824. provided as an abstraction to introspect on the capabilities of
  825. the spatial database. All of the attributes and routines provided by
  826. ``SpatialBackend`` are now a part of the ``ops`` attribute of the
  827. database backend.
  828. The old module ``django.contrib.gis.db.backend`` is still provided
  829. for backwards-compatibility access to a ``SpatialBackend`` object,
  830. which is just an alias to the ``ops`` module of the
  831. *default* spatial database connection.
  832. Users that were relying on undocumented modules and objects
  833. within ``django.contrib.gis.db.backend``, rather the abstractions
  834. provided by ``SpatialBackend``, are required to modify their code.
  835. For example, the following import which would work in 1.1 and
  836. below::
  837. from django.contrib.gis.db.backend.postgis import PostGISAdaptor
  838. Would need to be changed::
  839. from django.db import connection
  840. PostGISAdaptor = connection.ops.Adapter
  841. ``SpatialRefSys`` and ``GeometryColumns`` models
  842. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  843. In previous versions of GeoDjango, :mod:`django.contrib.gis.db.models`
  844. had ``SpatialRefSys`` and ``GeometryColumns`` models for querying
  845. the OGC spatial metadata tables ``spatial_ref_sys`` and ``geometry_columns``,
  846. respectively.
  847. While these aliases are still provided, they are only for the
  848. *default* database connection and exist only if the default connection
  849. is using a supported spatial database backend.
  850. .. note::
  851. Because the table structure of the OGC spatial metadata tables
  852. differs across spatial databases, the ``SpatialRefSys`` and
  853. ``GeometryColumns`` models can no longer be associated with
  854. the ``gis`` application name. Thus, no models will be returned
  855. when using the ``get_models`` method in the following example:
  856. .. code-block:: pycon
  857. >>> from django.db.models import get_app, get_models
  858. >>> get_models(get_app('gis'))
  859. []
  860. To get the correct ``SpatialRefSys`` and ``GeometryColumns``
  861. for your spatial database use the methods provided by the spatial backend:
  862. .. code-block:: pycon
  863. >>> from django.db import connections
  864. >>> SpatialRefSys = connections['my_spatialite'].ops.spatial_ref_sys()
  865. >>> GeometryColumns = connections['my_postgis'].ops.geometry_columns()
  866. .. note::
  867. When using the models returned from the ``spatial_ref_sys()`` and
  868. ``geometry_columns()`` method, you'll still need to use the
  869. correct database alias when querying on the non-default connection.
  870. In other words, to ensure that the models in the example above
  871. use the correct database::
  872. sr_qs = SpatialRefSys.objects.using('my_spatialite').filter(...)
  873. gc_qs = GeometryColumns.objects.using('my_postgis').filter(...)
  874. Language code ``no``
  875. --------------------
  876. The currently used language code for Norwegian Bokmål ``no`` is being
  877. replaced by the more common language code ``nb``.
  878. Function-based template loaders
  879. -------------------------------
  880. Django 1.2 changes the template loading mechanism to use a class-based
  881. approach. Old style function-based template loaders will still work, but should
  882. be updated to use the new class-based template loaders.