1.2.txt 46 KB

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