1.6.txt 54 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221
  1. =========================
  2. Django 1.6 release notes
  3. =========================
  4. .. note::
  5. Dedicated to Malcolm Tredinnick
  6. On March 17, 2013, the Django project and the free software community lost
  7. a very dear friend and developer.
  8. Malcolm was a long-time contributor to Django, a model community member, a
  9. brilliant mind, and a friend. His contributions to Django — and to many other
  10. open source projects — are nearly impossible to enumerate. Many on the core
  11. Django team had their first patches reviewed by him; his mentorship enriched
  12. us. His consideration, patience, and dedication will always be an inspiration
  13. to us.
  14. This release of Django is for Malcolm.
  15. -- The Django Developers
  16. *November 6, 2013*
  17. Welcome to Django 1.6!
  18. These release notes cover the :ref:`new features <whats-new-1.6>`, as well as
  19. some :ref:`backwards incompatible changes <backwards-incompatible-1.6>` you'll
  20. want to be aware of when upgrading from Django 1.5 or older versions. We've
  21. also dropped some features, which are detailed in :ref:`our deprecation plan
  22. <deprecation-removed-in-1.6>`, and we've :ref:`begun the deprecation process
  23. for some features <deprecated-features-1.6>`.
  24. Python compatibility
  25. ====================
  26. Django 1.6, like Django 1.5, requires Python 2.6.5 or above. Python 3 is also
  27. officially supported. We **highly recommend** the latest minor release for each
  28. supported Python series (2.6.X, 2.7.X, 3.2.X, and 3.3.X).
  29. Django 1.6 will be the final release series to support Python 2.6; beginning
  30. with Django 1.7, the minimum supported Python version will be 2.7.
  31. Python 3.4 is not supported, but support will be added in Django 1.7.
  32. .. _whats-new-1.6:
  33. What's new in Django 1.6
  34. ========================
  35. Simplified default project and app templates
  36. --------------------------------------------
  37. The default templates used by :djadmin:`startproject` and :djadmin:`startapp`
  38. have been simplified and modernized. The :doc:`admin
  39. </ref/contrib/admin/index>` is now enabled by default in new projects; the
  40. :doc:`sites </ref/contrib/sites>` framework no longer is. :ref:`clickjacking
  41. prevention <clickjacking-prevention>` is now on and the database defaults to
  42. SQLite.
  43. If the default templates don't suit your tastes, you can use :ref:`custom
  44. project and app templates <custom-app-and-project-templates>`.
  45. Improved transaction management
  46. -------------------------------
  47. Django's transaction management was overhauled. Database-level autocommit is
  48. now turned on by default. This makes transaction handling more explicit and
  49. should improve performance. The existing APIs were deprecated, and new APIs
  50. were introduced, as described in the :doc:`transaction management docs
  51. </topics/db/transactions>`.
  52. Persistent database connections
  53. -------------------------------
  54. Django now supports reusing the same database connection for several requests.
  55. This avoids the overhead of re-establishing a connection at the beginning of
  56. each request. For backwards compatibility, this feature is disabled by
  57. default. See :ref:`persistent-database-connections` for details.
  58. Discovery of tests in any test module
  59. -------------------------------------
  60. Django 1.6 ships with a new test runner that allows more flexibility in the
  61. location of tests. The previous runner
  62. (``django.test.simple.DjangoTestSuiteRunner``) found tests only in the
  63. ``models.py`` and ``tests.py`` modules of a Python package in
  64. :setting:`INSTALLED_APPS`.
  65. The new runner (``django.test.runner.DiscoverRunner``) uses the test discovery
  66. features built into ``unittest2`` (the version of ``unittest`` in the
  67. Python 2.7+ standard library, and bundled with Django). With test discovery,
  68. tests can be located in any module whose name matches the pattern ``test*.py``.
  69. In addition, the test labels provided to ``./manage.py test`` to nominate
  70. specific tests to run must now be full Python dotted paths (or directory
  71. paths), rather than ``applabel.TestCase.test_method_name`` pseudo-paths. This
  72. allows running tests located anywhere in your codebase, rather than only in
  73. :setting:`INSTALLED_APPS`. For more details, see :doc:`/topics/testing/index`.
  74. This change is backwards-incompatible; see the :ref:`backwards-incompatibility
  75. notes<new-test-runner>`.
  76. Time zone aware aggregation
  77. ---------------------------
  78. The support for :doc:`time zones </topics/i18n/timezones>` introduced in
  79. Django 1.4 didn't work well with :meth:`QuerySet.dates()
  80. <django.db.models.query.QuerySet.dates>`: aggregation was always performed in
  81. UTC. This limitation was lifted in Django 1.6. Use :meth:`QuerySet.datetimes()
  82. <django.db.models.query.QuerySet.datetimes>` to perform time zone aware
  83. aggregation on a :class:`~django.db.models.DateTimeField`.
  84. Support for savepoints in SQLite
  85. --------------------------------
  86. Django 1.6 adds support for savepoints in SQLite, with some :ref:`limitations
  87. <savepoints-in-sqlite>`.
  88. ``BinaryField`` model field
  89. ---------------------------
  90. A new :class:`django.db.models.BinaryField` model field allows storage of raw
  91. binary data in the database.
  92. GeoDjango form widgets
  93. ----------------------
  94. GeoDjango now provides :doc:`form fields and widgets </ref/contrib/gis/forms-api>`
  95. for its geo-specialized fields. They are OpenLayers-based by default, but they
  96. can be customized to use any other JS framework.
  97. ``check`` management command added for verifying compatibility
  98. --------------------------------------------------------------
  99. A :djadmin:`check` management command was added, enabling you to verify if your
  100. current configuration (currently oriented at settings) is compatible with the
  101. current version of Django.
  102. :meth:`Model.save() <django.db.models.Model.save()>` algorithm changed
  103. ----------------------------------------------------------------------
  104. The :meth:`Model.save() <django.db.models.Model.save()>` method now
  105. tries to directly ``UPDATE`` the database if the instance has a primary
  106. key value. Previously ``SELECT`` was performed to determine if ``UPDATE``
  107. or ``INSERT`` were needed. The new algorithm needs only one query for
  108. updating an existing row while the old algorithm needed two. See
  109. :meth:`Model.save() <django.db.models.Model.save()>` for more details.
  110. In some rare cases the database doesn't report that a matching row was
  111. found when doing an ``UPDATE``. An example is the PostgreSQL ``ON UPDATE``
  112. trigger which returns ``NULL``. In such cases it is possible to set
  113. :attr:`django.db.models.Options.select_on_save` flag to force saving to
  114. use the old algorithm.
  115. Minor features
  116. --------------
  117. * Authentication backends can raise ``PermissionDenied`` to immediately fail
  118. the authentication chain.
  119. * The ``HttpOnly`` flag can be set on the CSRF cookie with
  120. :setting:`CSRF_COOKIE_HTTPONLY`.
  121. * The :meth:`~django.test.TransactionTestCase.assertQuerysetEqual` now checks
  122. for undefined order and raises :exc:`ValueError` if undefined
  123. order is spotted. The order is seen as undefined if the given ``QuerySet``
  124. isn't ordered and there are more than one ordered values to compare against.
  125. * Added :meth:`~django.db.models.query.QuerySet.earliest` for symmetry with
  126. :meth:`~django.db.models.query.QuerySet.latest`.
  127. * In addition to :lookup:`year`, :lookup:`month` and :lookup:`day`, the ORM
  128. now supports :lookup:`hour`, :lookup:`minute` and :lookup:`second` lookups.
  129. * Django now wraps all :pep:`249` exceptions.
  130. * The default widgets for :class:`~django.forms.EmailField`,
  131. :class:`~django.forms.URLField`, :class:`~django.forms.IntegerField`,
  132. :class:`~django.forms.FloatField` and :class:`~django.forms.DecimalField` use
  133. the new type attributes available in HTML5 (``type='email'``, ``type='url'``,
  134. ``type='number'``). Note that due to erratic support of the ``number``
  135. input type with localized numbers in current browsers, Django only uses it
  136. when numeric fields are not localized.
  137. * The ``number`` argument for :ref:`lazy plural translations
  138. <lazy-plural-translations>` can be provided at translation time rather than
  139. at definition time.
  140. * For custom management commands: Verification of the presence of valid
  141. settings in commands that ask for it by using the
  142. ``BaseCommand.can_import_settings`` internal
  143. option is now performed independently from handling of the locale that
  144. should be active during the execution of the command. The latter can now be
  145. influenced by the new
  146. ``BaseCommand.leave_locale_alone`` internal
  147. option. See :ref:`management-commands-and-locales` for more details.
  148. * The :attr:`~django.views.generic.edit.DeletionMixin.success_url` of
  149. :class:`~django.views.generic.edit.DeletionMixin` is now interpolated with
  150. its ``object``’s ``__dict__``.
  151. * :class:`~django.http.HttpResponseRedirect` and
  152. :class:`~django.http.HttpResponsePermanentRedirect` now provide an ``url``
  153. attribute (equivalent to the URL the response will redirect to).
  154. * The ``MemcachedCache`` cache backend now uses the latest :mod:`pickle`
  155. protocol available.
  156. * Added :class:`~django.contrib.messages.views.SuccessMessageMixin` which
  157. provides a ``success_message`` attribute for
  158. :class:`~django.views.generic.edit.FormView` based classes.
  159. * Added the :attr:`django.db.models.ForeignKey.db_constraint` and
  160. :attr:`django.db.models.ManyToManyField.db_constraint` options.
  161. * The jQuery library embedded in the admin has been upgraded to version 1.9.1.
  162. * Syndication feeds (:mod:`django.contrib.syndication`) can now pass extra
  163. context through to feed templates using a new
  164. :meth:`Feed.get_context_data()
  165. <django.contrib.syndication.Feed.get_context_data>` callback.
  166. * The admin list columns have a ``column-<field_name>`` class in the HTML
  167. so the columns header can be styled with CSS, e.g. to set a column width.
  168. * The :ref:`isolation level<database-isolation-level>` can be customized under
  169. PostgreSQL.
  170. * The :ttag:`blocktrans` template tag now respects
  171. ``TEMPLATE_STRING_IF_INVALID`` for variables not present in the
  172. context, just like other template constructs.
  173. * ``SimpleLazyObject``\s will now present more helpful representations in shell
  174. debugging situations.
  175. * Generic :class:`~django.contrib.gis.db.models.GeometryField` is now editable
  176. with the OpenLayers widget in the admin.
  177. * The documentation contains a :doc:`deployment checklist
  178. </howto/deployment/checklist>`.
  179. * The :djadmin:`diffsettings` command gained a ``--all`` option.
  180. * ``django.forms.fields.Field.__init__`` now calls ``super()``, allowing
  181. field mixins to implement ``__init__()`` methods that will reliably be
  182. called.
  183. * The ``validate_max`` parameter was added to ``BaseFormSet`` and
  184. :func:`~django.forms.formsets.formset_factory`, and ``ModelForm`` and inline
  185. versions of the same. The behavior of validation for formsets with
  186. ``max_num`` was clarified. The previously undocumented behavior that
  187. hardened formsets against memory exhaustion attacks was documented,
  188. and the undocumented limit of the higher of 1000 or ``max_num`` forms
  189. was changed so it is always 1000 more than ``max_num``.
  190. * Added ``BCryptSHA256PasswordHasher`` to resolve the password truncation issue
  191. with bcrypt.
  192. * `Pillow`_ is now the preferred image manipulation library to use with Django.
  193. `PIL`_ is pending deprecation (support to be removed in Django 1.8).
  194. To upgrade, you should **first** uninstall PIL, **then** install Pillow.
  195. .. _`Pillow`: https://pypi.org/project/Pillow/
  196. .. _`PIL`: https://pypi.org/project/PIL/
  197. * :class:`~django.forms.ModelForm` accepts several new ``Meta``
  198. options.
  199. * Fields included in the ``localized_fields`` list will be localized
  200. (by setting ``localize`` on the form field).
  201. * The ``labels``, ``help_texts`` and ``error_messages`` options may be used
  202. to customize the default fields, see
  203. :ref:`modelforms-overriding-default-fields` for details.
  204. * The ``choices`` argument to model fields now accepts an iterable of iterables
  205. instead of requiring an iterable of lists or tuples.
  206. * The reason phrase can be customized in HTTP responses using
  207. :attr:`~django.http.HttpResponse.reason_phrase`.
  208. * When giving the URL of the next page for
  209. ``django.contrib.auth.views.logout()``,
  210. ``django.contrib.auth.views.password_reset()``,
  211. ``django.contrib.auth.views.password_reset_confirm()``,
  212. and ``django.contrib.auth.views.password_change()``, you can now pass
  213. URL names and they will be resolved.
  214. * The new :option:`dumpdata --pks` option specifies the primary keys of objects
  215. to dump. This option can only be used with one model.
  216. * Added ``QuerySet`` methods :meth:`~django.db.models.query.QuerySet.first`
  217. and :meth:`~django.db.models.query.QuerySet.last` which are convenience
  218. methods returning the first or last object matching the filters. Returns
  219. ``None`` if there are no objects matching.
  220. * :class:`~django.views.generic.base.View` and
  221. :class:`~django.views.generic.base.RedirectView` now support HTTP ``PATCH``
  222. method.
  223. * ``GenericForeignKey`` now takes an optional ``for_concrete_model`` argument,
  224. which when set to ``False`` allows the field to reference proxy models. The
  225. default is ``True`` to retain the old behavior.
  226. * The :class:`~django.middleware.locale.LocaleMiddleware` now stores the active
  227. language in session if it is not present there. This prevents loss of
  228. language settings after session flush, e.g. logout.
  229. * :exc:`~django.core.exceptions.SuspiciousOperation` has been differentiated
  230. into a number of subclasses, and each will log to a matching named logger
  231. under the ``django.security`` logging hierarchy. Along with this change,
  232. a ``handler400`` mechanism and default view are used whenever
  233. a ``SuspiciousOperation`` reaches the WSGI handler to return an
  234. ``HttpResponseBadRequest``.
  235. * The :exc:`~django.db.models.Model.DoesNotExist` exception now includes a
  236. message indicating the name of the attribute used for the lookup.
  237. * The :meth:`~django.db.models.query.QuerySet.get_or_create` method no longer
  238. requires at least one keyword argument.
  239. * The :class:`~django.test.SimpleTestCase` class includes a new assertion
  240. helper for testing formset errors:
  241. :meth:`~django.test.SimpleTestCase.assertFormsetError`.
  242. * The list of related fields added to a
  243. :class:`~django.db.models.query.QuerySet` by
  244. :meth:`~django.db.models.query.QuerySet.select_related` can be cleared using
  245. ``select_related(None)``.
  246. * The :meth:`~django.contrib.admin.InlineModelAdmin.get_extra` and
  247. :meth:`~django.contrib.admin.InlineModelAdmin.get_max_num` methods on
  248. :class:`~django.contrib.admin.InlineModelAdmin` may be overridden to
  249. customize the extra and maximum number of inline forms.
  250. * Formsets now have a
  251. :meth:`~django.forms.formsets.BaseFormSet.total_error_count` method.
  252. * :class:`~django.forms.ModelForm` fields can now override error messages
  253. defined in model fields by using the
  254. :attr:`~django.forms.Field.error_messages` argument of a ``Field``’s
  255. constructor. To take advantage of this new feature with your custom fields,
  256. :ref:`see the updated recommendation <raising-validation-error>` for raising
  257. a ``ValidationError``.
  258. * :class:`~django.contrib.admin.ModelAdmin` now preserves filters on the list view
  259. after creating, editing or deleting an object. It's possible to restore the previous
  260. behavior of clearing filters by setting the
  261. :attr:`~django.contrib.admin.ModelAdmin.preserve_filters` attribute to ``False``.
  262. * Added
  263. :meth:`FormMixin.get_prefix<django.views.generic.edit.FormMixin.get_prefix>`
  264. (which returns
  265. :attr:`FormMixin.prefix<django.views.generic.edit.FormMixin.prefix>` by
  266. default) to allow customizing the :attr:`~django.forms.Form.prefix` of the
  267. form.
  268. * Raw queries (``Manager.raw()`` or ``cursor.execute()``) can now use the
  269. "pyformat" parameter style, where placeholders in the query are given as
  270. ``'%(name)s'`` and the parameters are passed as a dictionary rather than
  271. a list (except on SQLite). This has long been possible (but not officially
  272. supported) on MySQL and PostgreSQL, and is now also available on Oracle.
  273. * The default iteration count for the PBKDF2 password hasher has been
  274. increased by 20%. This backwards compatible change will not affect
  275. existing passwords or users who have subclassed
  276. ``django.contrib.auth.hashers.PBKDF2PasswordHasher`` to change the
  277. default value. Passwords :ref:`will be upgraded <password-upgrades>` to use
  278. the new iteration count as necessary.
  279. .. _backwards-incompatible-1.6:
  280. Backwards incompatible changes in 1.6
  281. =====================================
  282. .. warning::
  283. In addition to the changes outlined in this section, be sure to review the
  284. :ref:`deprecation plan <deprecation-removed-in-1.6>` for any features that
  285. have been removed. If you haven't updated your code within the
  286. deprecation timeline for a given feature, its removal may appear as a
  287. backwards incompatible change.
  288. New transaction management model
  289. --------------------------------
  290. Behavior changes
  291. ~~~~~~~~~~~~~~~~
  292. Database-level autocommit is enabled by default in Django 1.6. While this
  293. doesn't change the general spirit of Django's transaction management, there
  294. are a few backwards-incompatibilities.
  295. Savepoints and ``assertNumQueries``
  296. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  297. The changes in transaction management may result in additional statements to
  298. create, release or rollback savepoints. This is more likely to happen with
  299. SQLite, since it didn't support savepoints until this release.
  300. If tests using :meth:`~django.test.TransactionTestCase.assertNumQueries` fail
  301. because of a higher number of queries than expected, check that the extra
  302. queries are related to savepoints, and adjust the expected number of queries
  303. accordingly.
  304. Autocommit option for PostgreSQL
  305. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  306. In previous versions, database-level autocommit was only an option for
  307. PostgreSQL, and it was disabled by default. This option is now ignored and can
  308. be removed.
  309. .. _new-test-runner:
  310. New test runner
  311. ---------------
  312. In order to maintain greater consistency with Python's ``unittest`` module, the
  313. new test runner (``django.test.runner.DiscoverRunner``) does not automatically
  314. support some types of tests that were supported by the previous runner:
  315. * Tests in ``models.py`` and ``tests/__init__.py`` files will no longer be
  316. found and run. Move them to a file whose name begins with ``test``.
  317. * Doctests will no longer be automatically discovered. To integrate doctests in
  318. your test suite, follow the :ref:`recommendations in the Python documentation
  319. <doctest-unittest-api>`.
  320. Django bundles a modified version of the :mod:`doctest` module from the Python
  321. standard library (in ``django.test._doctest``) and includes some additional
  322. doctest utilities. These utilities are deprecated and will be removed in Django
  323. 1.8; doctest suites should be updated to work with the standard library's
  324. doctest module (or converted to ``unittest``-compatible tests).
  325. If you wish to delay updates to your test suite, you can set your
  326. :setting:`TEST_RUNNER` setting to ``django.test.simple.DjangoTestSuiteRunner``
  327. to fully restore the old test behavior. ``DjangoTestSuiteRunner`` is deprecated
  328. but will not be removed from Django until version 1.8.
  329. Removal of ``django.contrib.gis.tests.GeoDjangoTestSuiteRunner`` GeoDjango custom test runner
  330. ---------------------------------------------------------------------------------------------
  331. This is for developers working on the GeoDjango application itself and related
  332. to the item above about changes in the test runners:
  333. The ``django.contrib.gis.tests.GeoDjangoTestSuiteRunner`` test runner has been
  334. removed and the standalone GeoDjango tests execution setup it implemented isn't
  335. supported anymore. To run the GeoDjango tests simply use the new
  336. ``DiscoverRunner`` and specify the ``django.contrib.gis`` app.
  337. Custom user models in tests
  338. ---------------------------
  339. The introduction of the new test runner has also slightly changed the way that
  340. test models are imported. As a result, any test that overrides ``AUTH_USER_MODEL``
  341. to test behavior with one of Django's test user models (
  342. ``django.contrib.auth.tests.custom_user.CustomUser`` and
  343. ``django.contrib.auth.tests.custom_user.ExtensionUser``) must now
  344. explicitly import the User model in your test module::
  345. from django.contrib.auth.tests.custom_user import CustomUser
  346. @override_settings(AUTH_USER_MODEL='auth.CustomUser')
  347. class CustomUserFeatureTests(TestCase):
  348. def test_something(self):
  349. # Test code here ...
  350. This import forces the custom user model to be registered. Without this import,
  351. the test will be unable to swap in the custom user model, and you will get an
  352. error reporting::
  353. ImproperlyConfigured: AUTH_USER_MODEL refers to model 'auth.CustomUser' that has not been installed
  354. Time zone-aware ``day``, ``month``, and ``week_day`` lookups
  355. ------------------------------------------------------------
  356. Django 1.6 introduces time zone support for :lookup:`day`, :lookup:`month`,
  357. and :lookup:`week_day` lookups when :setting:`USE_TZ` is ``True``. These
  358. lookups were previously performed in UTC regardless of the current time zone.
  359. This requires :ref:`time zone definitions in the database
  360. <database-time-zone-definitions>`. If you're using SQLite, you must install
  361. pytz_. If you're using MySQL, you must install pytz_ and load the time zone
  362. tables with `mysql_tzinfo_to_sql`_.
  363. .. _pytz: http://pytz.sourceforge.net/
  364. .. _mysql_tzinfo_to_sql: https://dev.mysql.com/doc/refman/en/mysql-tzinfo-to-sql.html
  365. Addition of ``QuerySet.datetimes()``
  366. ------------------------------------
  367. When the :doc:`time zone support </topics/i18n/timezones>` added in Django 1.4
  368. was active, :meth:`QuerySet.dates() <django.db.models.query.QuerySet.dates>`
  369. lookups returned unexpected results, because the aggregation was performed in
  370. UTC. To fix this, Django 1.6 introduces a new API, :meth:`QuerySet.datetimes()
  371. <django.db.models.query.QuerySet.datetimes>`. This requires a few changes in
  372. your code.
  373. ``QuerySet.dates()`` returns ``date`` objects
  374. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  375. :meth:`QuerySet.dates() <django.db.models.query.QuerySet.dates>` now returns a
  376. list of :class:`~datetime.date`. It used to return a list of
  377. :class:`~datetime.datetime`.
  378. :meth:`QuerySet.datetimes() <django.db.models.query.QuerySet.datetimes>`
  379. returns a list of :class:`~datetime.datetime`.
  380. ``QuerySet.dates()`` no longer usable on ``DateTimeField``
  381. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  382. :meth:`QuerySet.dates() <django.db.models.query.QuerySet.dates>` raises an
  383. error if it's used on :class:`~django.db.models.DateTimeField` when time
  384. zone support is active. Use :meth:`QuerySet.datetimes()
  385. <django.db.models.query.QuerySet.datetimes>` instead.
  386. ``date_hierarchy`` requires time zone definitions
  387. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  388. The :attr:`~django.contrib.admin.ModelAdmin.date_hierarchy` feature of the
  389. admin now relies on :meth:`QuerySet.datetimes()
  390. <django.db.models.query.QuerySet.datetimes>` when it's used on a
  391. :class:`~django.db.models.DateTimeField`.
  392. This requires time zone definitions in the database when :setting:`USE_TZ` is
  393. ``True``. :ref:`Learn more <database-time-zone-definitions>`.
  394. ``date_list`` in generic views requires time zone definitions
  395. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  396. For the same reason, accessing ``date_list`` in the context of a date-based
  397. generic view requires time zone definitions in the database when the view is
  398. based on a :class:`~django.db.models.DateTimeField` and :setting:`USE_TZ` is
  399. ``True``. :ref:`Learn more <database-time-zone-definitions>`.
  400. New lookups may clash with model fields
  401. ---------------------------------------
  402. Django 1.6 introduces ``hour``, ``minute``, and ``second`` lookups on
  403. :class:`~django.db.models.DateTimeField`. If you had model fields called
  404. ``hour``, ``minute``, or ``second``, the new lookups will clash with you field
  405. names. Append an explicit :lookup:`exact` lookup if this is an issue.
  406. ``BooleanField`` no longer defaults to ``False``
  407. ------------------------------------------------
  408. When a :class:`~django.db.models.BooleanField` doesn't have an explicit
  409. :attr:`~django.db.models.Field.default`, the implicit default value is
  410. ``None``. In previous version of Django, it was ``False``, but that didn't
  411. represent accurately the lack of a value.
  412. Code that relies on the default value being ``False`` may raise an exception
  413. when saving new model instances to the database, because ``None`` isn't an
  414. acceptable value for a :class:`~django.db.models.BooleanField`. You should
  415. either specify ``default=False`` in the field definition, or ensure the field
  416. is set to ``True`` or ``False`` before saving the object.
  417. Translations and comments in templates
  418. --------------------------------------
  419. Extraction of translations after comments
  420. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  421. Extraction of translatable literals from templates with the
  422. :djadmin:`makemessages` command now correctly detects i18n constructs when
  423. they are located after a ``{#`` / ``#}``-type comment on the same line. E.g.:
  424. .. code-block:: html+django
  425. {# A comment #}{% trans "This literal was incorrectly ignored. Not anymore" %}
  426. Location of translator comments
  427. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  428. :ref:`translator-comments-in-templates` specified using ``{#`` / ``#}`` need to
  429. be at the end of a line. If they are not, the comments are ignored and
  430. :djadmin:`makemessages` will generate a warning. For example:
  431. .. code-block:: html+django
  432. {# Translators: This is ignored #}{% trans "Translate me" %}
  433. {{ title }}{# Translators: Extracted and associated with 'Welcome' below #}
  434. <h1>{% trans "Welcome" %}</h1>
  435. Quoting in ``reverse()``
  436. ------------------------
  437. When reversing URLs, Django didn't apply ``django.utils.http.urlquote``
  438. to arguments before interpolating them in URL patterns. This bug is fixed in
  439. Django 1.6. If you worked around this bug by applying URL quoting before
  440. passing arguments to ``reverse()``, this may result in double-quoting. If this
  441. happens, simply remove the URL quoting from your code. You will also have to
  442. replace special characters in URLs used in
  443. :func:`~django.test.SimpleTestCase.assertRedirects` with their encoded
  444. versions.
  445. Storage of IP addresses in the comments app
  446. -------------------------------------------
  447. The comments app now uses a
  448. ``GenericIPAddressField`` for storing commenters' IP addresses, to support
  449. comments submitted from IPv6 addresses. Until now, it stored them in an
  450. ``IPAddressField``, which is only meant to support IPv4. When saving a comment
  451. made from an IPv6 address, the address would be silently truncated on MySQL
  452. databases, and raise an exception on Oracle. You will need to change the
  453. column type in your database to benefit from this change.
  454. For MySQL, execute this query on your project's database:
  455. .. code-block:: sql
  456. ALTER TABLE django_comments MODIFY ip_address VARCHAR(39);
  457. For Oracle, execute this query:
  458. .. code-block:: sql
  459. ALTER TABLE DJANGO_COMMENTS MODIFY (ip_address VARCHAR2(39));
  460. If you do not apply this change, the behavior is unchanged: on MySQL, IPv6
  461. addresses are silently truncated; on Oracle, an exception is generated. No
  462. database change is needed for SQLite or PostgreSQL databases.
  463. Percent literals in ``cursor.execute`` queries
  464. ----------------------------------------------
  465. When you are running raw SQL queries through the
  466. :ref:`cursor.execute <executing-custom-sql>` method, the rule about doubling
  467. percent literals (``%``) inside the query has been unified. Past behavior
  468. depended on the database backend. Now, across all backends, you only need to
  469. double literal percent characters if you are also providing replacement
  470. parameters. For example::
  471. # No parameters, no percent doubling
  472. cursor.execute("SELECT foo FROM bar WHERE baz = '30%'")
  473. # Parameters passed, non-placeholders have to be doubled
  474. cursor.execute("SELECT foo FROM bar WHERE baz = '30%%' and id = %s", [self.id])
  475. ``SQLite`` users need to check and update such queries.
  476. .. _m2m-help_text:
  477. Help text of model form fields for ManyToManyField fields
  478. ---------------------------------------------------------
  479. HTML rendering of model form fields corresponding to
  480. :class:`~django.db.models.ManyToManyField` model fields used to get the
  481. hard-coded sentence:
  482. *Hold down "Control", or "Command" on a Mac, to select more than one.*
  483. (or its translation to the active locale) imposed as the help legend shown along
  484. them if neither :attr:`model <django.db.models.Field.help_text>` nor :attr:`form
  485. <django.forms.Field.help_text>` ``help_text`` attributes were specified by the
  486. user (or this string was appended to any ``help_text`` that was provided).
  487. Since this happened at the model layer, there was no way to prevent the text
  488. from appearing in cases where it wasn't applicable such as form fields that
  489. implement user interactions that don't involve a keyboard and/or a mouse.
  490. Starting with Django 1.6, as an ad-hoc temporary backward-compatibility
  491. provision, the logic to add the "Hold down..." sentence has been moved to the
  492. model form field layer and modified to add the text only when the associated
  493. widget is :class:`~django.forms.SelectMultiple` or selected subclasses.
  494. The change can affect you in a backward incompatible way if you employ custom
  495. model form fields and/or widgets for ``ManyToManyField`` model fields whose UIs
  496. do rely on the automatic provision of the mentioned hard-coded sentence. These
  497. form field implementations need to adapt to the new scenario by providing their
  498. own handling of the ``help_text`` attribute.
  499. Applications that use Django :doc:`model form </topics/forms/modelforms>`
  500. facilities together with Django built-in form :doc:`fields </ref/forms/fields>`
  501. and :doc:`widgets </ref/forms/widgets>` aren't affected but need to be aware of
  502. what's described in :ref:`m2m-help_text-deprecation` below.
  503. QuerySet iteration
  504. ------------------
  505. The ``QuerySet`` iteration was changed to immediately convert all fetched
  506. rows to ``Model`` objects. In Django 1.5 and earlier the fetched rows were
  507. converted to ``Model`` objects in chunks of 100.
  508. Existing code will work, but the amount of rows converted to objects
  509. might change in certain use cases. Such usages include partially looping
  510. over a queryset or any usage which ends up doing ``__bool__`` or
  511. ``__contains__``.
  512. Notably most database backends did fetch all the rows in one go already in
  513. 1.5.
  514. It is still possible to convert the fetched rows to ``Model`` objects
  515. lazily by using the :meth:`~django.db.models.query.QuerySet.iterator()`
  516. method.
  517. :meth:`BoundField.label_tag<django.forms.BoundField.label_tag>` now includes the form's :attr:`~django.forms.Form.label_suffix`
  518. -------------------------------------------------------------------------------------------------------------------------------
  519. This is consistent with how methods like
  520. :meth:`Form.as_p<django.forms.Form.as_p>` and
  521. :meth:`Form.as_ul<django.forms.Form.as_ul>` render labels.
  522. If you manually render ``label_tag`` in your templates:
  523. .. code-block:: html+django
  524. {{ form.my_field.label_tag }}: {{ form.my_field }}
  525. you'll want to remove the colon (or whatever other separator you may be
  526. using) to avoid duplicating it when upgrading to Django 1.6. The following
  527. template in Django 1.6 will render identically to the above template in Django
  528. 1.5, except that the colon will appear inside the ``<label>`` element.
  529. .. code-block:: html+django
  530. {{ form.my_field.label_tag }} {{ form.my_field }}
  531. will render something like:
  532. .. code-block:: html
  533. <label for="id_my_field">My Field:</label> <input id="id_my_field" type="text" name="my_field" />
  534. If you want to keep the current behavior of rendering ``label_tag`` without
  535. the ``label_suffix``, instantiate the form ``label_suffix=''``. You can also
  536. customize the ``label_suffix`` on a per-field basis using the new
  537. ``label_suffix`` parameter on :meth:`~django.forms.BoundField.label_tag`.
  538. Admin views ``_changelist_filters`` GET parameter
  539. -------------------------------------------------
  540. To achieve preserving and restoring list view filters, admin views now
  541. pass around the ``_changelist_filters`` GET parameter. It's important that you
  542. account for that change if you have custom admin templates or if your tests
  543. rely on the previous URLs. If you want to revert to the original behavior you
  544. can set the
  545. :attr:`~django.contrib.admin.ModelAdmin.preserve_filters` attribute to ``False``.
  546. ``django.contrib.auth`` password reset uses base 64 encoding of ``User`` PK
  547. ---------------------------------------------------------------------------
  548. Past versions of Django used base 36 encoding of the ``User`` primary key in
  549. the password reset views and URLs
  550. (``django.contrib.auth.views.password_reset_confirm()``). Base 36 encoding is
  551. sufficient if the user primary key is an integer, however, with the
  552. introduction of custom user models in Django 1.5, that assumption may no longer
  553. be true.
  554. ``django.contrib.auth.views.password_reset_confirm()`` has been modified to
  555. take a ``uidb64`` parameter instead of ``uidb36``. If you are reversing this
  556. view, for example in a custom ``password_reset_email.html`` template, be sure
  557. to update your code.
  558. A temporary shim for ``django.contrib.auth.views.password_reset_confirm()``
  559. that will allow password reset links generated prior to Django 1.6 to continue
  560. to work has been added to provide backwards compatibility; this will be removed
  561. in Django 1.7. Thus, as long as your site has been running Django 1.6 for more
  562. than ``PASSWORD_RESET_TIMEOUT_DAYS``, this change will have no effect.
  563. If not (for example, if you upgrade directly from Django 1.5 to Django 1.7),
  564. then any password reset links generated before you upgrade to Django 1.7 or
  565. later won't work after the upgrade.
  566. In addition, if you have any custom password reset URLs, you will need to
  567. update them by replacing ``uidb36`` with ``uidb64`` and the dash that follows
  568. that pattern with a slash. Also add ``_\-`` to the list of characters that may
  569. match the ``uidb64`` pattern.
  570. For example::
  571. url(r'^reset/(?P<uidb36>[0-9A-Za-z]+)-(?P<token>.+)/$',
  572. 'django.contrib.auth.views.password_reset_confirm',
  573. name='password_reset_confirm'),
  574. becomes::
  575. url(r'^reset/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>.+)/$',
  576. 'django.contrib.auth.views.password_reset_confirm',
  577. name='password_reset_confirm'),
  578. You may also want to add the shim to support the old style reset links. Using
  579. the example above, you would modify the existing url by replacing
  580. ``django.contrib.auth.views.password_reset_confirm`` with
  581. ``django.contrib.auth.views.password_reset_confirm_uidb36`` and also remove
  582. the ``name`` argument so it doesn't conflict with the new url::
  583. url(r'^reset/(?P<uidb36>[0-9A-Za-z]+)-(?P<token>.+)/$',
  584. 'django.contrib.auth.views.password_reset_confirm_uidb36'),
  585. You can remove this URL pattern after your app has been deployed with Django
  586. 1.6 for ``PASSWORD_RESET_TIMEOUT_DAYS``.
  587. Default session serialization switched to JSON
  588. ----------------------------------------------
  589. Historically, :mod:`django.contrib.sessions` used :mod:`pickle` to serialize
  590. session data before storing it in the backend. If you're using the :ref:`signed
  591. cookie session backend<cookie-session-backend>` and :setting:`SECRET_KEY` is
  592. known by an attacker (there isn't an inherent vulnerability in Django that
  593. would cause it to leak), the attacker could insert a string into their session
  594. which, when unpickled, executes arbitrary code on the server. The technique for
  595. doing so is simple and easily available on the internet. Although the cookie
  596. session storage signs the cookie-stored data to prevent tampering, a
  597. :setting:`SECRET_KEY` leak immediately escalates to a remote code execution
  598. vulnerability.
  599. This attack can be mitigated by serializing session data using JSON rather
  600. than :mod:`pickle`. To facilitate this, Django 1.5.3 introduced a new setting,
  601. :setting:`SESSION_SERIALIZER`, to customize the session serialization format.
  602. For backwards compatibility, this setting defaulted to using :mod:`pickle`
  603. in Django 1.5.3, but we've changed the default to JSON in 1.6. If you upgrade
  604. and switch from pickle to JSON, sessions created before the upgrade will be
  605. lost. While JSON serialization does not support all Python objects like
  606. :mod:`pickle` does, we highly recommend using JSON-serialized sessions. Be
  607. aware of the following when checking your code to determine if JSON
  608. serialization will work for your application:
  609. * JSON requires string keys, so you will likely run into problems if you are
  610. using non-string keys in ``request.session``.
  611. * Setting session expiration by passing ``datetime`` values to
  612. :meth:`~django.contrib.sessions.backends.base.SessionBase.set_expiry` will
  613. not work as ``datetime`` values are not serializable in JSON. You can use
  614. integer values instead.
  615. See the :ref:`session_serialization` documentation for more details.
  616. Object Relational Mapper changes
  617. --------------------------------
  618. Django 1.6 contains many changes to the ORM. These changes fall mostly in
  619. three categories:
  620. 1. Bug fixes (e.g. proper join clauses for generic relations, query combining,
  621. join promotion, and join trimming fixes)
  622. 2. Preparation for new features. For example the ORM is now internally ready
  623. for multicolumn foreign keys.
  624. 3. General cleanup.
  625. These changes can result in some compatibility problems. For example, some
  626. queries will now generate different table aliases. This can affect
  627. :meth:`QuerySet.extra() <django.db.models.query.QuerySet.extra>`. In addition
  628. some queries will now produce different results. An example is
  629. :meth:`exclude(condition) <django.db.models.query.QuerySet.exclude>`
  630. where the condition is a complex one (referencing multijoins inside
  631. :class:`Q objects <django.db.models.Q>`). In many cases the affected
  632. queries didn't produce correct results in Django 1.5 but do now.
  633. Unfortunately there are also cases that produce different results, but
  634. neither Django 1.5 nor 1.6 produce correct results.
  635. Finally, there have been many changes to the ORM internal APIs.
  636. Miscellaneous
  637. -------------
  638. * The ``django.db.models.query.EmptyQuerySet`` can't be instantiated any more -
  639. it is only usable as a marker class for checking if
  640. :meth:`~django.db.models.query.QuerySet.none` has been called:
  641. ``isinstance(qs.none(), EmptyQuerySet)``
  642. * If your CSS/JavaScript code used to access HTML input widgets by type, you
  643. should review it as ``type='text'`` widgets might be now output as
  644. ``type='email'``, ``type='url'`` or ``type='number'`` depending on their
  645. corresponding field type.
  646. * Form field's :attr:`~django.forms.Field.error_messages` that contain a
  647. placeholder should now always use a named placeholder (``"Value '%(value)s' is
  648. too big"`` instead of ``"Value '%s' is too big"``). See the corresponding
  649. field documentation for details about the names of the placeholders. The
  650. changes in 1.6 particularly affect :class:`~django.forms.DecimalField` and
  651. :class:`~django.forms.ModelMultipleChoiceField`.
  652. * Some :attr:`~django.forms.Field.error_messages` for
  653. :class:`~django.forms.IntegerField`, :class:`~django.forms.EmailField`,
  654. ``IPAddressField``, :class:`~django.forms.GenericIPAddressField`, and
  655. :class:`~django.forms.SlugField` have been suppressed because they
  656. duplicated error messages already provided by validators tied to the fields.
  657. * Due to a change in the form validation workflow,
  658. :class:`~django.forms.TypedChoiceField` ``coerce`` method should always
  659. return a value present in the ``choices`` field attribute. That limitation
  660. should be lift again in Django 1.7.
  661. * There have been changes in the way timeouts are handled in cache backends.
  662. Explicitly passing in ``timeout=None`` no longer results in using the
  663. default timeout. It will now set a non-expiring timeout. Passing 0 into the
  664. memcache backend no longer uses the default timeout, and now will
  665. set-and-expire-immediately the value.
  666. * The ``django.contrib.flatpages`` app used to set custom HTTP headers for
  667. debugging purposes. This functionality was not documented and made caching
  668. ineffective so it has been removed, along with its generic implementation,
  669. previously available in ``django.core.xheaders``.
  670. * The ``XViewMiddleware`` has been moved from ``django.middleware.doc`` to
  671. ``django.contrib.admindocs.middleware`` because it is an implementation
  672. detail of admindocs, proven not to be reusable in general.
  673. * :class:`~django.db.models.GenericIPAddressField` will now only allow
  674. ``blank`` values if ``null`` values are also allowed. Creating a
  675. ``GenericIPAddressField`` where ``blank`` is allowed but ``null`` is not
  676. will trigger a model validation error because ``blank`` values are always
  677. stored as ``null``. Previously, storing a ``blank`` value in a field which
  678. did not allow ``null`` would cause a database exception at runtime.
  679. * If a ``NoReverseMatch`` exception is raised from a method when rendering a
  680. template, it is not silenced. For example, ``{{ obj.view_href }}`` will
  681. cause template rendering to fail if ``view_href()`` raises
  682. ``NoReverseMatch``. There is no change to the :ttag:`{% url %}<url>` tag, it
  683. causes template rendering to fail like always when ``NoReverseMatch`` is
  684. raised.
  685. * :meth:`django.test.Client.logout` now calls
  686. :meth:`django.contrib.auth.logout` which will send the
  687. :func:`~django.contrib.auth.signals.user_logged_out` signal.
  688. * :ref:`Authentication views <built-in-auth-views>` are now reversed by name,
  689. not their locations in ``django.contrib.auth.views``. If you are using the
  690. views without a ``name``, you should update your ``urlpatterns`` to use
  691. ``django.conf.urls.url()`` with the ``name`` parameter. For example::
  692. (r'^reset/done/$', 'django.contrib.auth.views.password_reset_complete')
  693. becomes::
  694. url(r'^reset/done/$', 'django.contrib.auth.views.password_reset_complete', name='password_reset_complete')
  695. * :class:`~django.views.generic.base.RedirectView` now has a ``pattern_name``
  696. attribute which allows it to choose the target by reversing the URL.
  697. * In Django 1.4 and 1.5, a blank string was unintentionally not considered to
  698. be a valid password. This meant
  699. :meth:`~django.contrib.auth.models.User.set_password()` would save a blank
  700. password as an unusable password like
  701. :meth:`~django.contrib.auth.models.User.set_unusable_password()` does, and
  702. thus :meth:`~django.contrib.auth.models.User.check_password()` always
  703. returned ``False`` for blank passwords. This has been corrected in this
  704. release: blank passwords are now valid.
  705. * The admin :attr:`~django.contrib.admin.ModelAdmin.changelist_view` previously
  706. accepted a ``pop`` GET parameter to signify it was to be displayed in a popup.
  707. This parameter has been renamed to ``_popup`` to be consistent with the rest
  708. of the admin views. You should update your custom templates if they use the
  709. previous parameter name.
  710. * :meth:`~django.core.validators.validate_email` now accepts email addresses
  711. with ``localhost`` as the domain.
  712. * The new :option:`makemessages --keep-pot` option prevents deleting the
  713. temporary .pot file generated before creating the .po file.
  714. * The undocumented ``django.core.servers.basehttp.WSGIServerException`` has
  715. been removed. Use ``socket.error`` provided by the standard library instead.
  716. This change was also released in Django 1.5.5.
  717. * The signature of :meth:`django.views.generic.base.RedirectView.get_redirect_url`
  718. has changed and now accepts positional arguments as well (``*args, **kwargs``).
  719. Any unnamed captured group will now be passed to ``get_redirect_url()``
  720. which may result in a ``TypeError`` if you don't update the signature of your
  721. custom method.
  722. .. _deprecated-features-1.6:
  723. Features deprecated in 1.6
  724. ==========================
  725. Transaction management APIs
  726. ---------------------------
  727. Transaction management was completely overhauled in Django 1.6, and the
  728. current APIs are deprecated:
  729. - ``django.middleware.transaction.TransactionMiddleware``
  730. - ``django.db.transaction.autocommit``
  731. - ``django.db.transaction.commit_on_success``
  732. - ``django.db.transaction.commit_manually``
  733. - the ``TRANSACTIONS_MANAGED`` setting
  734. ``django.contrib.comments``
  735. ---------------------------
  736. Django's comment framework has been deprecated and is no longer supported. It
  737. will be available in Django 1.6 and 1.7, and removed in Django 1.8. Most users
  738. will be better served with a custom solution, or a hosted product like Disqus__.
  739. The code formerly known as ``django.contrib.comments`` is `still available
  740. in an external repository`__.
  741. __ https://disqus.com/
  742. __ https://github.com/django/django-contrib-comments
  743. Support for PostgreSQL versions older than 8.4
  744. ----------------------------------------------
  745. The end of upstream support periods was reached in December 2011 for
  746. PostgreSQL 8.2 and in February 2013 for 8.3. As a consequence, Django 1.6 sets
  747. 8.4 as the minimum PostgreSQL version it officially supports.
  748. You're strongly encouraged to use the most recent version of PostgreSQL
  749. available, because of performance improvements and to take advantage of the
  750. native streaming replication available in PostgreSQL 9.x.
  751. Changes to :ttag:`cycle` and :ttag:`firstof`
  752. --------------------------------------------
  753. The template system generally escapes all variables to avoid XSS attacks.
  754. However, due to an accident of history, the :ttag:`cycle` and :ttag:`firstof`
  755. tags render their arguments as-is.
  756. Django 1.6 starts a process to correct this inconsistency. The ``future``
  757. template library provides alternate implementations of :ttag:`cycle` and
  758. :ttag:`firstof` that autoescape their inputs. If you're using these tags,
  759. you're encouraged to include the following line at the top of your templates to
  760. enable the new behavior::
  761. {% load cycle from future %}
  762. or::
  763. {% load firstof from future %}
  764. The tags implementing the old behavior have been deprecated, and in Django
  765. 1.8, the old behavior will be replaced with the new behavior. To ensure
  766. compatibility with future versions of Django, existing templates should be
  767. modified to use the ``future`` versions.
  768. If necessary, you can temporarily disable auto-escaping with
  769. :func:`~django.utils.safestring.mark_safe` or :ttag:`{% autoescape off %}
  770. <autoescape>`.
  771. ``CACHE_MIDDLEWARE_ANONYMOUS_ONLY`` setting
  772. -------------------------------------------
  773. ``CacheMiddleware`` and ``UpdateCacheMiddleware`` used to provide a way to
  774. cache requests only if they weren't made by a logged-in user. This mechanism
  775. was largely ineffective because the middleware correctly takes into account the
  776. ``Vary: Cookie`` HTTP header, and this header is being set on a variety of
  777. occasions, such as:
  778. * accessing the session, or
  779. * using CSRF protection, which is turned on by default, or
  780. * using a client-side library which sets cookies, like `Google Analytics`__.
  781. This makes the cache effectively work on a per-session basis regardless of the
  782. ``CACHE_MIDDLEWARE_ANONYMOUS_ONLY`` setting.
  783. __ https://www.google.com/analytics/
  784. ``SEND_BROKEN_LINK_EMAILS`` setting
  785. -----------------------------------
  786. :class:`~django.middleware.common.CommonMiddleware` used to provide basic
  787. reporting of broken links by email when ``SEND_BROKEN_LINK_EMAILS`` is set to
  788. ``True``.
  789. Because of intractable ordering problems between
  790. :class:`~django.middleware.common.CommonMiddleware` and
  791. :class:`~django.middleware.locale.LocaleMiddleware`, this feature was split
  792. out into a new middleware:
  793. :class:`~django.middleware.common.BrokenLinkEmailsMiddleware`.
  794. If you're relying on this feature, you should add
  795. ``'django.middleware.common.BrokenLinkEmailsMiddleware'`` to your
  796. ``MIDDLEWARE_CLASSES`` setting and remove ``SEND_BROKEN_LINK_EMAILS``
  797. from your settings.
  798. ``_has_changed`` method on widgets
  799. ----------------------------------
  800. If you defined your own form widgets and defined the ``_has_changed`` method
  801. on a widget, you should now define this method on the form field itself.
  802. ``module_name`` model _meta attribute
  803. -------------------------------------
  804. ``Model._meta.module_name`` was renamed to ``model_name``. Despite being a
  805. private API, it will go through a regular deprecation path.
  806. ``get_(add|change|delete)_permission`` model _meta methods
  807. ----------------------------------------------------------
  808. ``Model._meta.get_(add|change|delete)_permission`` methods were deprecated.
  809. Even if they were not part of the public API they'll also go through
  810. a regular deprecation path. You can replace them with
  811. ``django.contrib.auth.get_permission_codename('action', Model._meta)`` where
  812. ``'action'`` is ``'add'``, ``'change'``, or ``'delete'``.
  813. ``get_query_set`` and similar methods renamed to ``get_queryset``
  814. -----------------------------------------------------------------
  815. Methods that return a ``QuerySet`` such as ``Manager.get_query_set`` or
  816. ``ModelAdmin.queryset`` have been renamed to ``get_queryset``.
  817. If you are writing a library that implements, for example, a
  818. ``Manager.get_query_set`` method, and you need to support old Django versions,
  819. you should rename the method and conditionally add an alias with the old name::
  820. class CustomManager(models.Manager):
  821. def get_queryset(self):
  822. pass # ...
  823. if django.VERSION < (1, 6):
  824. get_query_set = get_queryset
  825. # For Django >= 1.6, models.Manager provides a get_query_set fallback
  826. # that emits a warning when used.
  827. If you are writing a library that needs to call the ``get_queryset`` method and
  828. must support old Django versions, you should write::
  829. get_queryset = (some_manager.get_query_set
  830. if hasattr(some_manager, 'get_query_set')
  831. else some_manager.get_queryset)
  832. return get_queryset() # etc
  833. In the general case of a custom manager that both implements its own
  834. ``get_queryset`` method and calls that method, and needs to work with older Django
  835. versions, and libraries that have not been updated yet, it is useful to define
  836. a ``get_queryset_compat`` method as below and use it internally to your manager::
  837. class YourCustomManager(models.Manager):
  838. def get_queryset(self):
  839. return YourCustomQuerySet() # for example
  840. if django.VERSION < (1, 6):
  841. get_query_set = get_queryset
  842. def active(self): # for example
  843. return self.get_queryset_compat().filter(active=True)
  844. def get_queryset_compat(self):
  845. get_queryset = (self.get_query_set
  846. if hasattr(self, 'get_query_set')
  847. else self.get_queryset)
  848. return get_queryset()
  849. This helps to minimize the changes that are needed, but also works correctly in
  850. the case of subclasses (such as ``RelatedManagers`` from Django 1.5) which might
  851. override either ``get_query_set`` or ``get_queryset``.
  852. ``shortcut`` view and URLconf
  853. -----------------------------
  854. The ``shortcut`` view was moved from ``django.views.defaults`` to
  855. ``django.contrib.contenttypes.views`` shortly after the 1.0 release, but the
  856. old location was never deprecated. This oversight was corrected in Django 1.6
  857. and you should now use the new location.
  858. The URLconf ``django.conf.urls.shortcut`` was also deprecated. If you're
  859. including it in an URLconf, simply replace::
  860. (r'^prefix/', include('django.conf.urls.shortcut')),
  861. with::
  862. (r'^prefix/(?P<content_type_id>\d+)/(?P<object_id>.*)/$', 'django.contrib.contenttypes.views.shortcut'),
  863. ``ModelForm`` without ``fields`` or ``exclude``
  864. -----------------------------------------------
  865. Previously, if you wanted a :class:`~django.forms.ModelForm` to use all fields on
  866. the model, you could simply omit the ``Meta.fields`` attribute, and all fields
  867. would be used.
  868. This can lead to security problems where fields are added to the model and,
  869. unintentionally, automatically become editable by end users. In some cases,
  870. particular with boolean fields, it is possible for this problem to be completely
  871. invisible. This is a form of `Mass assignment vulnerability
  872. <https://en.wikipedia.org/wiki/Mass_assignment_vulnerability>`_.
  873. For this reason, this behavior is deprecated, and using the ``Meta.exclude``
  874. option is strongly discouraged. Instead, all fields that are intended for
  875. inclusion in the form should be listed explicitly in the ``fields`` attribute.
  876. If this security concern really does not apply in your case, there is a shortcut
  877. to explicitly indicate that all fields should be used - use the special value
  878. ``"__all__"`` for the fields attribute::
  879. class MyModelForm(ModelForm):
  880. class Meta:
  881. fields = "__all__"
  882. model = MyModel
  883. If you have custom ``ModelForms`` that only need to be used in the admin, there
  884. is another option. The admin has its own methods for defining fields
  885. (``fieldsets`` etc.), and so adding a list of fields to the ``ModelForm`` is
  886. redundant. Instead, simply omit the ``Meta`` inner class of the ``ModelForm``,
  887. or omit the ``Meta.model`` attribute. Since the ``ModelAdmin`` subclass knows
  888. which model it is for, it can add the necessary attributes to derive a
  889. functioning ``ModelForm``. This behavior also works for earlier Django
  890. versions.
  891. ``UpdateView`` and ``CreateView`` without explicit fields
  892. ---------------------------------------------------------
  893. The generic views :class:`~django.views.generic.edit.CreateView` and
  894. :class:`~django.views.generic.edit.UpdateView`, and anything else derived from
  895. :class:`~django.views.generic.edit.ModelFormMixin`, are vulnerable to the
  896. security problem described in the section above, because they can automatically
  897. create a ``ModelForm`` that uses all fields for a model.
  898. For this reason, if you use these views for editing models, you must also supply
  899. the ``fields`` attribute (new in Django 1.6), which is a list of model fields
  900. and works in the same way as the :class:`~django.forms.ModelForm`
  901. ``Meta.fields`` attribute. Alternatively, you can set the ``form_class``
  902. attribute to a ``ModelForm`` that explicitly defines the fields to be used.
  903. Defining an ``UpdateView`` or ``CreateView`` subclass to be used with a model
  904. but without an explicit list of fields is deprecated.
  905. .. _m2m-help_text-deprecation:
  906. Munging of help text of model form fields for ``ManyToManyField`` fields
  907. ------------------------------------------------------------------------
  908. All special handling of the ``help_text`` attribute of ``ManyToManyField`` model
  909. fields performed by standard model or model form fields as described in
  910. :ref:`m2m-help_text` above is deprecated and will be removed in Django 1.8.
  911. Help text of these fields will need to be handled either by applications, custom
  912. form fields or widgets, just like happens with the rest of the model field
  913. types.