1.2.txt 46 KB

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