1.9.txt 61 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527
  1. ========================
  2. Django 1.9 release notes
  3. ========================
  4. *December 1, 2015*
  5. Welcome to Django 1.9!
  6. These release notes cover the :ref:`new features <whats-new-1.9>`, as well as
  7. some :ref:`backwards incompatible changes <backwards-incompatible-1.9>` you'll
  8. want to be aware of when upgrading from Django 1.8 or older versions. We've
  9. :ref:`dropped some features<removed-features-1.9>` that have reached the end of
  10. their deprecation cycle, and we've :ref:`begun the deprecation process for some
  11. features <deprecated-features-1.9>`.
  12. See the :doc:`/howto/upgrade-version` guide if you're updating an existing
  13. project.
  14. Python compatibility
  15. ====================
  16. Django 1.9 requires Python 2.7, 3.4, or 3.5. We **highly recommend** and only
  17. officially support the latest release of each series.
  18. The Django 1.8 series is the last to support Python 3.2 and 3.3.
  19. .. _whats-new-1.9:
  20. What's new in Django 1.9
  21. ========================
  22. Performing actions after a transaction commit
  23. ---------------------------------------------
  24. The new :func:`~django.db.transaction.on_commit` hook allows performing actions
  25. after a database transaction is successfully committed. This is useful for
  26. tasks such as sending notification emails, creating queued tasks, or
  27. invalidating caches.
  28. This functionality from the :pypi:`django-transaction-hooks` package has been
  29. integrated into Django.
  30. Password validation
  31. -------------------
  32. Django now offers password validation to help prevent the usage of weak
  33. passwords by users. The validation is integrated in the included password
  34. change and reset forms and is simple to integrate in any other code.
  35. Validation is performed by one or more validators, configured in the new
  36. :setting:`AUTH_PASSWORD_VALIDATORS` setting.
  37. Four validators are included in Django, which can enforce a minimum length,
  38. compare the password to the user's attributes like their name, ensure
  39. passwords aren't entirely numeric, or check against an included list of common
  40. passwords. You can combine multiple validators, and some validators have
  41. custom configuration options. For example, you can choose to provide a custom
  42. list of common passwords. Each validator provides a help text to explain its
  43. requirements to the user.
  44. By default, no validation is performed and all passwords are accepted, so if
  45. you don't set :setting:`AUTH_PASSWORD_VALIDATORS`, you will not see any
  46. change. In new projects created with the default :djadmin:`startproject`
  47. template, a simple set of validators is enabled. To enable basic validation in
  48. the included auth forms for your project, you could set, for example::
  49. AUTH_PASSWORD_VALIDATORS = [
  50. {
  51. "NAME": "django.contrib.auth.password_validation.UserAttributeSimilarityValidator",
  52. },
  53. {
  54. "NAME": "django.contrib.auth.password_validation.MinimumLengthValidator",
  55. },
  56. {
  57. "NAME": "django.contrib.auth.password_validation.CommonPasswordValidator",
  58. },
  59. {
  60. "NAME": "django.contrib.auth.password_validation.NumericPasswordValidator",
  61. },
  62. ]
  63. See :ref:`password-validation` for more details.
  64. Permission mixins for class-based views
  65. ---------------------------------------
  66. Django now ships with the mixins
  67. :class:`~django.contrib.auth.mixins.AccessMixin`,
  68. :class:`~django.contrib.auth.mixins.LoginRequiredMixin`,
  69. :class:`~django.contrib.auth.mixins.PermissionRequiredMixin`, and
  70. :class:`~django.contrib.auth.mixins.UserPassesTestMixin` to provide the
  71. functionality of the ``django.contrib.auth.decorators`` for class-based views.
  72. These mixins have been taken from, or are at least inspired by, the
  73. `django-braces`_ project.
  74. There are a few differences between Django's and ``django-braces``\'
  75. implementation, though:
  76. * The :attr:`~django.contrib.auth.mixins.AccessMixin.raise_exception` attribute
  77. can only be ``True`` or ``False``. Custom exceptions or callables are not
  78. supported.
  79. * The :meth:`~django.contrib.auth.mixins.AccessMixin.handle_no_permission`
  80. method does not take a ``request`` argument. The current request is available
  81. in ``self.request``.
  82. * The custom ``test_func()`` of :class:`~django.contrib.auth.mixins.UserPassesTestMixin`
  83. does not take a ``user`` argument. The current user is available in
  84. ``self.request.user``.
  85. * The :attr:`permission_required <django.contrib.auth.mixins.PermissionRequiredMixin>`
  86. attribute supports a string (defining one permission) or a list/tuple of
  87. strings (defining multiple permissions) that need to be fulfilled to grant
  88. access.
  89. * The new :attr:`~django.contrib.auth.mixins.AccessMixin.permission_denied_message`
  90. attribute allows passing a message to the ``PermissionDenied`` exception.
  91. .. _django-braces: https://django-braces.readthedocs.io/en/latest/index.html
  92. New styling for ``contrib.admin``
  93. ---------------------------------
  94. The admin sports a modern, flat design with new SVG icons which look perfect
  95. on HiDPI screens. It still provides a fully-functional experience to `YUI's
  96. A-grade`_ browsers. Older browser may experience varying levels of graceful
  97. degradation.
  98. .. _YUI's A-grade: https://github.com/yui/yui3/wiki/Graded-Browser-Support
  99. Running tests in parallel
  100. -------------------------
  101. The :djadmin:`test` command now supports a :option:`--parallel <test
  102. --parallel>` option to run a project's tests in multiple processes in parallel.
  103. Each process gets its own database. You must ensure that different test cases
  104. don't access the same resources. For instance, test cases that touch the
  105. filesystem should create a temporary directory for their own use.
  106. This option is enabled by default for Django's own test suite provided:
  107. - the OS supports it (all but Windows)
  108. - the database backend supports it (all the built-in backends but Oracle)
  109. Minor features
  110. --------------
  111. :mod:`django.contrib.admin`
  112. ~~~~~~~~~~~~~~~~~~~~~~~~~~~
  113. * Admin views now have ``model_admin`` or ``admin_site`` attributes.
  114. * The URL of the admin change view has been changed (was at
  115. ``/admin/<app>/<model>/<pk>/`` by default and is now at
  116. ``/admin/<app>/<model>/<pk>/change/``). This should not affect your
  117. application unless you have hardcoded admin URLs. In that case, replace those
  118. links by :ref:`reversing admin URLs <admin-reverse-urls>` instead. Note that
  119. the old URL still redirects to the new one for backwards compatibility, but
  120. it may be removed in a future version.
  121. * :meth:`ModelAdmin.get_list_select_related()
  122. <django.contrib.admin.ModelAdmin.get_list_select_related>` was added to allow
  123. changing the ``select_related()`` values used in the admin's changelist query
  124. based on the request.
  125. * The ``available_apps`` context variable, which lists the available
  126. applications for the current user, has been added to the
  127. :meth:`AdminSite.each_context() <django.contrib.admin.AdminSite.each_context>`
  128. method.
  129. * :attr:`AdminSite.empty_value_display
  130. <django.contrib.admin.AdminSite.empty_value_display>` and
  131. :attr:`ModelAdmin.empty_value_display
  132. <django.contrib.admin.ModelAdmin.empty_value_display>` were added to override
  133. the display of empty values in admin change list. You can also customize the
  134. value for each field.
  135. * Added jQuery events :ref:`when an inline form is added or removed
  136. <admin-javascript-inline-form-events>` on the change form page.
  137. * The time picker widget includes a '6 p.m' option for consistency of having
  138. predefined options every 6 hours.
  139. * JavaScript slug generation now supports Romanian characters.
  140. :mod:`django.contrib.admindocs`
  141. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  142. * The model section of the ``admindocs`` now also describes methods that take
  143. arguments, rather than ignoring them.
  144. :mod:`django.contrib.auth`
  145. ~~~~~~~~~~~~~~~~~~~~~~~~~~
  146. * The default iteration count for the PBKDF2 password hasher has been increased
  147. by 20%. This backwards compatible change will not affect users who have
  148. subclassed ``django.contrib.auth.hashers.PBKDF2PasswordHasher`` to change the
  149. default value.
  150. * The ``BCryptSHA256PasswordHasher`` will now update passwords if its
  151. ``rounds`` attribute is changed.
  152. * ``AbstractBaseUser`` and ``BaseUserManager`` were moved to a new
  153. ``django.contrib.auth.base_user`` module so that they can be imported without
  154. including ``django.contrib.auth`` in :setting:`INSTALLED_APPS` (doing so
  155. raised a deprecation warning in older versions and is no longer supported in
  156. Django 1.9).
  157. * The permission argument of
  158. :func:`~django.contrib.auth.decorators.permission_required()` accepts all
  159. kinds of iterables, not only list and tuples.
  160. * The new :class:`~django.contrib.auth.middleware.PersistentRemoteUserMiddleware`
  161. makes it possible to use ``REMOTE_USER`` for setups where the header is only
  162. populated on login pages instead of every request in the session.
  163. * The ``django.contrib.auth.views.password_reset()`` view accepts an
  164. ``extra_email_context`` parameter.
  165. :mod:`django.contrib.contenttypes`
  166. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  167. * It's now possible to use
  168. :attr:`~django.db.models.Options.order_with_respect_to` with a
  169. ``GenericForeignKey``.
  170. :mod:`django.contrib.gis`
  171. ~~~~~~~~~~~~~~~~~~~~~~~~~
  172. * All ``GeoQuerySet`` methods have been deprecated and replaced by
  173. :doc:`equivalent database functions </ref/contrib/gis/functions>`. As soon
  174. as the legacy methods have been replaced in your code, you should even be
  175. able to remove the special ``GeoManager`` from your GIS-enabled classes.
  176. * The GDAL interface now supports instantiating file-based and in-memory
  177. :ref:`GDALRaster objects <raster-data-source-objects>` from raw data.
  178. Setters for raster properties such as projection or pixel values have
  179. been added.
  180. * For PostGIS users, the new :class:`~django.contrib.gis.db.models.RasterField`
  181. allows :ref:`storing GDALRaster objects <creating-and-saving-raster-models>`.
  182. It supports automatic spatial index creation and reprojection when saving a
  183. model. It does not yet support spatial querying.
  184. * The new :meth:`GDALRaster.warp() <django.contrib.gis.gdal.GDALRaster.warp>`
  185. method allows warping a raster by specifying target raster properties such as
  186. origin, width, height, or pixel size (among others).
  187. * The new :meth:`GDALRaster.transform()
  188. <django.contrib.gis.gdal.GDALRaster.transform>` method allows transforming a
  189. raster into a different spatial reference system by specifying a target
  190. ``srid``.
  191. * The new :class:`~django.contrib.gis.geoip2.GeoIP2` class allows using
  192. MaxMind's GeoLite2 databases which includes support for IPv6 addresses.
  193. * The default OpenLayers library version included in widgets has been updated
  194. from 2.13 to 2.13.1.
  195. :mod:`django.contrib.postgres`
  196. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  197. * Added support for the :lookup:`rangefield.contained_by` lookup for some built
  198. in fields which correspond to the range fields.
  199. * Added ``django.contrib.postgres.fields.JSONField``.
  200. * Added :doc:`/ref/contrib/postgres/aggregates`.
  201. * Added the :class:`~django.contrib.postgres.functions.TransactionNow` database
  202. function.
  203. :mod:`django.contrib.sessions`
  204. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  205. * The session model and ``SessionStore`` classes for the ``db`` and
  206. ``cached_db`` backends are refactored to allow a custom database session
  207. backend to build upon them. See
  208. :ref:`extending-database-backed-session-engines` for more details.
  209. :mod:`django.contrib.sites`
  210. ~~~~~~~~~~~~~~~~~~~~~~~~~~~
  211. * :func:`~django.contrib.sites.shortcuts.get_current_site` now handles the case
  212. where ``request.get_host()`` returns ``domain:port``, e.g.
  213. ``example.com:80``. If the lookup fails because the host does not match a
  214. record in the database and the host has a port, the port is stripped and the
  215. lookup is retried with the domain part only.
  216. :mod:`django.contrib.syndication`
  217. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  218. * Support for multiple enclosures per feed item has been added. If multiple
  219. enclosures are defined on a RSS feed, an exception is raised as RSS feeds,
  220. unlike Atom feeds, do not support multiple enclosures per feed item.
  221. Cache
  222. ~~~~~
  223. * ``django.core.cache.backends.base.BaseCache`` now has a ``get_or_set()``
  224. method.
  225. * :func:`django.views.decorators.cache.never_cache` now sends more persuasive
  226. headers (added ``no-cache, no-store, must-revalidate`` to ``Cache-Control``)
  227. to better prevent caching. This was also added in Django 1.8.8.
  228. CSRF
  229. ~~~~
  230. * The request header's name used for CSRF authentication can be customized
  231. with :setting:`CSRF_HEADER_NAME`.
  232. * The CSRF referer header is now validated against the
  233. :setting:`CSRF_COOKIE_DOMAIN` setting if set. See :ref:`how-csrf-works` for
  234. details.
  235. * The new :setting:`CSRF_TRUSTED_ORIGINS` setting provides a way to allow
  236. cross-origin unsafe requests (e.g. ``POST``) over HTTPS.
  237. Database backends
  238. ~~~~~~~~~~~~~~~~~
  239. * The PostgreSQL backend (``django.db.backends.postgresql_psycopg2``) is also
  240. available as ``django.db.backends.postgresql``. The old name will continue to
  241. be available for backwards compatibility.
  242. File Storage
  243. ~~~~~~~~~~~~
  244. * :meth:`Storage.get_valid_name()
  245. <django.core.files.storage.Storage.get_valid_name>` is now called when
  246. the :attr:`~django.db.models.FileField.upload_to` is a callable.
  247. * :class:`~django.core.files.File` now has the ``seekable()`` method when using
  248. Python 3.
  249. Forms
  250. ~~~~~
  251. * :class:`~django.forms.ModelForm` accepts the new ``Meta`` option
  252. ``field_classes`` to customize the type of the fields. See
  253. :ref:`modelforms-overriding-default-fields` for details.
  254. * You can now specify the order in which form fields are rendered with the
  255. :attr:`~django.forms.Form.field_order` attribute, the ``field_order``
  256. constructor argument , or the :meth:`~django.forms.Form.order_fields` method.
  257. * A form prefix can be specified inside a form class, not only when
  258. instantiating a form. See :ref:`form-prefix` for details.
  259. * You can now :ref:`specify keyword arguments <custom-formset-form-kwargs>`
  260. that you want to pass to the constructor of forms in a formset.
  261. * :class:`~django.forms.SlugField` now accepts an
  262. :attr:`~django.forms.SlugField.allow_unicode` argument to allow Unicode
  263. characters in slugs.
  264. * :class:`~django.forms.CharField` now accepts a
  265. :attr:`~django.forms.CharField.strip` argument to strip input data of leading
  266. and trailing whitespace. As this defaults to ``True`` this is different
  267. behavior from previous releases.
  268. * Form fields now support the :attr:`~django.forms.Field.disabled` argument,
  269. allowing the field widget to be displayed disabled by browsers.
  270. * It's now possible to customize bound fields by overriding a field's
  271. :meth:`~django.forms.Field.get_bound_field()` method.
  272. Generic Views
  273. ~~~~~~~~~~~~~
  274. * Class-based views generated using ``as_view()`` now have ``view_class``
  275. and ``view_initkwargs`` attributes.
  276. * :func:`~django.utils.decorators.method_decorator` can now be used with a list
  277. or tuple of decorators. It can also be used to :ref:`decorate classes instead
  278. of methods <decorating-class-based-views>`.
  279. Internationalization
  280. ~~~~~~~~~~~~~~~~~~~~
  281. * The :func:`django.views.i18n.set_language` view now properly redirects to
  282. :ref:`translated URLs <url-internationalization>`, when available.
  283. * The ``django.views.i18n.javascript_catalog()`` view now works correctly
  284. if used multiple times with different configurations on the same page.
  285. * The :func:`django.utils.timezone.make_aware` function gained an ``is_dst``
  286. argument to help resolve ambiguous times during DST transitions.
  287. * You can now use locale variants supported by gettext. These are usually used
  288. for languages which can be written in different scripts, for example Latin
  289. and Cyrillic (e.g. ``be@latin``).
  290. * Added the ``django.views.i18n.json_catalog()`` view to help build a custom
  291. client-side i18n library upon Django translations. It returns a JSON object
  292. containing a translations catalog, formatting settings, and a plural rule.
  293. * Added the ``name_translated`` attribute to the object returned by the
  294. :ttag:`get_language_info` template tag. Also added a corresponding template
  295. filter: :tfilter:`language_name_translated`.
  296. * You can now run :djadmin:`compilemessages` from the root directory of your
  297. project and it will find all the app message files that were created by
  298. :djadmin:`makemessages`.
  299. * :djadmin:`makemessages` now calls ``xgettext`` once per locale directory
  300. rather than once per translatable file. This speeds up localization builds.
  301. * :ttag:`blocktrans` supports assigning its output to a variable using
  302. ``asvar``.
  303. * Two new languages are available: Colombian Spanish and Scottish Gaelic.
  304. Management Commands
  305. ~~~~~~~~~~~~~~~~~~~
  306. * The new :djadmin:`sendtestemail` command lets you send a test email to
  307. easily confirm that email sending through Django is working.
  308. * To increase the readability of the SQL code generated by
  309. :djadmin:`sqlmigrate`, the SQL code generated for each migration operation is
  310. preceded by the operation's description.
  311. * The :djadmin:`dumpdata` command output is now deterministically ordered.
  312. Moreover, when the ``--output`` option is specified, it also shows a progress
  313. bar in the terminal.
  314. * The :djadmin:`createcachetable` command now has a ``--dry-run`` flag to
  315. print out the SQL rather than execute it.
  316. * The :djadmin:`startapp` command creates an ``apps.py`` file. Since it doesn't
  317. use ``default_app_config`` (:ref:`a discouraged API
  318. <configuring-applications-ref>`), you must specify the app config's path,
  319. e.g. ``'polls.apps.PollsConfig'``, in :setting:`INSTALLED_APPS` for it to be
  320. used (instead of just ``'polls'``).
  321. * When using the PostgreSQL backend, the :djadmin:`dbshell` command can connect
  322. to the database using the password from your settings file (instead of
  323. requiring it to be manually entered).
  324. * The ``django`` package may be run as a script, i.e. ``python -m django``,
  325. which will behave the same as ``django-admin``.
  326. * Management commands that have the ``--noinput`` option now also take
  327. ``--no-input`` as an alias for that option.
  328. Migrations
  329. ~~~~~~~~~~
  330. * Initial migrations are now marked with an :attr:`initial = True
  331. <django.db.migrations.Migration.initial>` class attribute which allows
  332. :option:`migrate --fake-initial` to more easily detect initial migrations.
  333. * Added support for serialization of ``functools.partial`` and ``LazyObject``
  334. instances.
  335. * When supplying ``None`` as a value in :setting:`MIGRATION_MODULES`, Django
  336. will consider the app an app without migrations.
  337. * When applying migrations, the "Rendering model states" step that's displayed
  338. when running migrate with verbosity 2 or higher now computes only the states
  339. for the migrations that have already been applied. The model states for
  340. migrations being applied are generated on demand, drastically reducing the
  341. amount of required memory.
  342. However, this improvement is not available when unapplying migrations and
  343. therefore still requires the precomputation and storage of the intermediate
  344. migration states.
  345. This improvement also requires that Django no longer supports mixed migration
  346. plans. Mixed plans consist of a list of migrations where some are being
  347. applied and others are being unapplied. This was never officially supported
  348. and never had a public API that supports this behavior.
  349. * The :djadmin:`squashmigrations` command now supports specifying the starting
  350. migration from which migrations will be squashed.
  351. Models
  352. ~~~~~~
  353. * :meth:`QuerySet.bulk_create() <django.db.models.query.QuerySet.bulk_create>`
  354. now works on proxy models.
  355. * Database configuration gained a :setting:`TIME_ZONE <DATABASE-TIME_ZONE>`
  356. option for interacting with databases that store datetimes in local time and
  357. don't support time zones when :setting:`USE_TZ` is ``True``.
  358. * Added the :meth:`RelatedManager.set()
  359. <django.db.models.fields.related.RelatedManager.set()>` method to the related
  360. managers created by ``ForeignKey``, ``GenericForeignKey``, and
  361. ``ManyToManyField``.
  362. * The :meth:`~django.db.models.fields.related.RelatedManager.add` method on
  363. a reverse foreign key now has a ``bulk`` parameter to allow executing one
  364. query regardless of the number of objects being added rather than one query
  365. per object.
  366. * Added the ``keep_parents`` parameter to :meth:`Model.delete()
  367. <django.db.models.Model.delete>` to allow deleting only a child's data in a
  368. model that uses multi-table inheritance.
  369. * :meth:`Model.delete() <django.db.models.Model.delete>`
  370. and :meth:`QuerySet.delete() <django.db.models.query.QuerySet.delete>` return
  371. the number of objects deleted.
  372. * Added a system check to prevent defining both ``Meta.ordering`` and
  373. ``order_with_respect_to`` on the same model.
  374. * :lookup:`Date and time <year>` lookups can be chained with other lookups
  375. (such as :lookup:`exact`, :lookup:`gt`, :lookup:`lt`, etc.). For example:
  376. ``Entry.objects.filter(pub_date__month__gt=6)``.
  377. * Time lookups (hour, minute, second) are now supported by
  378. :class:`~django.db.models.TimeField` for all database backends. Support for
  379. backends other than SQLite was added but undocumented in Django 1.7.
  380. * You can specify the ``output_field`` parameter of the
  381. :class:`~django.db.models.Avg` aggregate in order to aggregate over
  382. non-numeric columns, such as ``DurationField``.
  383. * Added the :lookup:`date` lookup to :class:`~django.db.models.DateTimeField`
  384. to allow querying the field by only the date portion.
  385. * Added the :class:`~django.db.models.functions.Greatest` and
  386. :class:`~django.db.models.functions.Least` database functions.
  387. * Added the :class:`~django.db.models.functions.Now` database function, which
  388. returns the current date and time.
  389. * :class:`~django.db.models.Transform` is now a subclass of
  390. :ref:`Func() <func-expressions>` which allows ``Transform``\s to be used on
  391. the right hand side of an expression, just like regular ``Func``\s. This
  392. allows registering some database functions like
  393. :class:`~django.db.models.functions.Length`,
  394. :class:`~django.db.models.functions.Lower`, and
  395. :class:`~django.db.models.functions.Upper` as transforms.
  396. * :class:`~django.db.models.SlugField` now accepts an
  397. :attr:`~django.db.models.SlugField.allow_unicode` argument to allow Unicode
  398. characters in slugs.
  399. * Added support for referencing annotations in ``QuerySet.distinct()``.
  400. * ``connection.queries`` shows queries with substituted parameters on SQLite.
  401. * :doc:`Query expressions </ref/models/expressions>` can now be used when
  402. creating new model instances using ``save()``, ``create()``, and
  403. ``bulk_create()``.
  404. Requests and Responses
  405. ~~~~~~~~~~~~~~~~~~~~~~
  406. * Unless :attr:`HttpResponse.reason_phrase
  407. <django.http.HttpResponse.reason_phrase>` is explicitly set, it now is
  408. determined by the current value of :attr:`HttpResponse.status_code
  409. <django.http.HttpResponse.status_code>`. Modifying the value of
  410. ``status_code`` outside of the constructor will also modify the value of
  411. ``reason_phrase``.
  412. * The debug view now shows details of chained exceptions on Python 3.
  413. * The default 40x error views now accept a second positional parameter, the
  414. exception that triggered the view.
  415. * View error handlers now support
  416. :class:`~django.template.response.TemplateResponse`, commonly used with
  417. class-based views.
  418. * Exceptions raised by the ``render()`` method are now passed to the
  419. ``process_exception()`` method of each middleware.
  420. * Request middleware can now set :attr:`HttpRequest.urlconf
  421. <django.http.HttpRequest.urlconf>` to ``None`` to revert any changes made
  422. by previous middleware and return to using the :setting:`ROOT_URLCONF`.
  423. * The :setting:`DISALLOWED_USER_AGENTS` check in
  424. :class:`~django.middleware.common.CommonMiddleware` now raises a
  425. :class:`~django.core.exceptions.PermissionDenied` exception as opposed to
  426. returning an :class:`~django.http.HttpResponseForbidden` so that
  427. :data:`~django.conf.urls.handler403` is invoked.
  428. * Added :meth:`HttpRequest.get_port() <django.http.HttpRequest.get_port>` to
  429. fetch the originating port of the request.
  430. * Added the ``json_dumps_params`` parameter to
  431. :class:`~django.http.JsonResponse` to allow passing keyword arguments to the
  432. ``json.dumps()`` call used to generate the response.
  433. * The :class:`~django.middleware.common.BrokenLinkEmailsMiddleware` now
  434. ignores 404s when the referer is equal to the requested URL. To circumvent
  435. the empty referer check already implemented, some web bots set the referer to
  436. the requested URL.
  437. Templates
  438. ~~~~~~~~~
  439. * Template tags created with the :meth:`~django.template.Library.simple_tag`
  440. helper can now store results in a template variable by using the ``as``
  441. argument.
  442. * Added a :meth:`Context.setdefault() <django.template.Context.setdefault>`
  443. method.
  444. * The :ref:`django.template <django-template-logger>` logger was added and
  445. includes the following messages:
  446. * A ``DEBUG`` level message for missing context variables.
  447. * A ``WARNING`` level message for uncaught exceptions raised
  448. during the rendering of an ``{% include %}`` when debug mode is off
  449. (helpful since ``{% include %}`` silences the exception and returns an
  450. empty string).
  451. * The :ttag:`firstof` template tag supports storing the output in a variable
  452. using 'as'.
  453. * :meth:`Context.update() <django.template.Context.update>` can now be used as
  454. a context manager.
  455. * Django template loaders can now extend templates recursively.
  456. * The debug page template postmortem now include output from each engine that
  457. is installed.
  458. * :ref:`Debug page integration <template-debug-integration>` for custom
  459. template engines was added.
  460. * The :class:`~django.template.backends.django.DjangoTemplates` backend gained
  461. the ability to register libraries and builtins explicitly through the
  462. template :setting:`OPTIONS <TEMPLATES-OPTIONS>`.
  463. * The ``timesince`` and ``timeuntil`` filters were improved to deal with leap
  464. years when given large time spans.
  465. * The ``include`` tag now caches parsed templates objects during template
  466. rendering, speeding up reuse in places such as for loops.
  467. Tests
  468. ~~~~~
  469. * Added the :meth:`json() <django.test.Response.json>` method to test client
  470. responses to give access to the response body as JSON.
  471. * Added the :meth:`~django.test.Client.force_login()` method to the test
  472. client. Use this method to simulate the effect of a user logging into the
  473. site while skipping the authentication and verification steps of
  474. :meth:`~django.test.Client.login()`.
  475. URLs
  476. ~~~~
  477. * Regular expression lookaround assertions are now allowed in URL patterns.
  478. * The application namespace can now be set using an ``app_name`` attribute
  479. on the included module or object. It can also be set by passing a 2-tuple
  480. of (<list of patterns>, <application namespace>) as the first argument to
  481. ``include()``.
  482. * System checks have been added for common URL pattern mistakes.
  483. Validators
  484. ~~~~~~~~~~
  485. * Added :func:`django.core.validators.int_list_validator` to generate
  486. validators of strings containing integers separated with a custom character.
  487. * :class:`~django.core.validators.EmailValidator` now limits the length of
  488. domain name labels to 63 characters per :rfc:`1034`.
  489. * Added :func:`~django.core.validators.validate_unicode_slug` to validate slugs
  490. that may contain Unicode characters.
  491. .. _backwards-incompatible-1.9:
  492. Backwards incompatible changes in 1.9
  493. =====================================
  494. .. warning::
  495. In addition to the changes outlined in this section, be sure to review the
  496. :ref:`removed-features-1.9` for the features that have reached the end of
  497. their deprecation cycle and therefore been removed. If you haven't updated
  498. your code within the deprecation timeline for a given feature, its removal
  499. may appear as a backwards incompatible change.
  500. Database backend API
  501. --------------------
  502. * A couple of new tests rely on the ability of the backend to introspect column
  503. defaults (returning the result as ``Field.default``). You can set the
  504. ``can_introspect_default`` database feature to ``False`` if your backend
  505. doesn't implement this. You may want to review the implementation on the
  506. backends that Django includes for reference (:ticket:`24245`).
  507. * Registering a global adapter or converter at the level of the DB-API module
  508. to handle time zone information of :class:`~datetime.datetime` values passed
  509. as query parameters or returned as query results on databases that don't
  510. support time zones is discouraged. It can conflict with other libraries.
  511. The recommended way to add a time zone to :class:`~datetime.datetime` values
  512. fetched from the database is to register a converter for ``DateTimeField``
  513. in ``DatabaseOperations.get_db_converters()``.
  514. The ``needs_datetime_string_cast`` database feature was removed. Database
  515. backends that set it must register a converter instead, as explained above.
  516. * The ``DatabaseOperations.value_to_db_<type>()`` methods were renamed to
  517. ``adapt_<type>field_value()`` to mirror the ``convert_<type>field_value()``
  518. methods.
  519. * To use the new ``date`` lookup, third-party database backends may need to
  520. implement the ``DatabaseOperations.datetime_cast_date_sql()`` method.
  521. * The ``DatabaseOperations.time_extract_sql()`` method was added. It calls the
  522. existing ``date_extract_sql()`` method. This method is overridden by the
  523. SQLite backend to add time lookups (hour, minute, second) to
  524. :class:`~django.db.models.TimeField`, and may be needed by third-party
  525. database backends.
  526. * The ``DatabaseOperations.datetime_cast_sql()`` method (not to be confused
  527. with ``DatabaseOperations.datetime_cast_date_sql()`` mentioned above)
  528. has been removed. This method served to format dates on Oracle long
  529. before 1.0, but hasn't been overridden by any core backend in years
  530. and hasn't been called anywhere in Django's code or tests.
  531. * In order to support test parallelization, you must implement the
  532. ``DatabaseCreation._clone_test_db()`` method and set
  533. ``DatabaseFeatures.can_clone_databases = True``. You may have to adjust
  534. ``DatabaseCreation.get_test_db_clone_settings()``.
  535. Default settings that were tuples are now lists
  536. -----------------------------------------------
  537. The default settings in ``django.conf.global_settings`` were a combination of
  538. lists and tuples. All settings that were formerly tuples are now lists.
  539. ``is_usable`` attribute on template loaders is removed
  540. ------------------------------------------------------
  541. Django template loaders previously required an ``is_usable`` attribute to be
  542. defined. If a loader was configured in the template settings and this attribute
  543. was ``False``, the loader would be silently ignored. In practice, this was only
  544. used by the egg loader to detect if ``setuptools`` was installed. The
  545. ``is_usable`` attribute is now removed and the egg loader instead fails at
  546. runtime if ``setuptools`` is not installed.
  547. Related set direct assignment
  548. -----------------------------
  549. Direct assignment of related objects in the ORM used to perform a ``clear()``
  550. followed by a call to ``add()``. This caused needlessly large data changes and
  551. prevented using the :data:`~django.db.models.signals.m2m_changed` signal to
  552. track individual changes in many-to-many relations.
  553. Direct assignment now relies on the new
  554. :meth:`~django.db.models.fields.related.RelatedManager.set` method on related
  555. managers which by default only processes changes between the existing related
  556. set and the one that's newly assigned. The previous behavior can be restored by
  557. replacing direct assignment by a call to ``set()`` with the keyword argument
  558. ``clear=True``.
  559. ``ModelForm``, and therefore ``ModelAdmin``, internally rely on direct
  560. assignment for many-to-many relations and as a consequence now use the new
  561. behavior.
  562. Filesystem-based template loaders catch more specific exceptions
  563. ----------------------------------------------------------------
  564. When using the :class:`filesystem.Loader <django.template.loaders.filesystem.Loader>`
  565. or :class:`app_directories.Loader <django.template.loaders.app_directories.Loader>`
  566. template loaders, earlier versions of Django raised a
  567. :exc:`~django.template.TemplateDoesNotExist` error if a template source existed
  568. but was unreadable. This could happen under many circumstances, such as if
  569. Django didn't have permissions to open the file, or if the template source was
  570. a directory. Now, Django only silences the exception if the template source
  571. does not exist. All other situations result in the original ``IOError`` being
  572. raised.
  573. HTTP redirects no longer forced to absolute URIs
  574. ------------------------------------------------
  575. Relative redirects are no longer converted to absolute URIs. :rfc:`2616`
  576. required the ``Location`` header in redirect responses to be an absolute URI,
  577. but it has been superseded by :rfc:`7231` which allows relative URIs in
  578. ``Location``, recognizing the actual practice of user agents, almost all of
  579. which support them.
  580. Consequently, the expected URLs passed to ``assertRedirects`` should generally
  581. no longer include the scheme and domain part of the URLs. For example,
  582. ``self.assertRedirects(response, 'http://testserver/some-url/')`` should be
  583. replaced by ``self.assertRedirects(response, '/some-url/')`` (unless the
  584. redirection specifically contained an absolute URL).
  585. In the rare case that you need the old behavior (discovered with an ancient
  586. version of Apache with ``mod_scgi`` that interprets a relative redirect as an
  587. "internal redirect"), you can restore it by writing a custom middleware::
  588. class LocationHeaderFix(object):
  589. def process_response(self, request, response):
  590. if "Location" in response:
  591. response["Location"] = request.build_absolute_uri(response["Location"])
  592. return response
  593. Dropped support for PostgreSQL 9.0
  594. ----------------------------------
  595. Upstream support for PostgreSQL 9.0 ended in September 2015. As a consequence,
  596. Django 1.9 sets 9.1 as the minimum PostgreSQL version it officially supports.
  597. Dropped support for Oracle 11.1
  598. -------------------------------
  599. Upstream support for Oracle 11.1 ended in August 2015. As a consequence, Django
  600. 1.9 sets 11.2 as the minimum Oracle version it officially supports.
  601. Bulk behavior of ``add()`` method of related managers
  602. -----------------------------------------------------
  603. To improve performance, the ``add()`` methods of the related managers created
  604. by ``ForeignKey`` and ``GenericForeignKey`` changed from a series of
  605. ``Model.save()`` calls to a single ``QuerySet.update()`` call. The change means
  606. that ``pre_save`` and ``post_save`` signals aren't sent anymore. You can use
  607. the ``bulk=False`` keyword argument to revert to the previous behavior.
  608. Template ``LoaderOrigin`` and ``StringOrigin`` are removed
  609. ----------------------------------------------------------
  610. In previous versions of Django, when a template engine was initialized with
  611. debug as ``True``, an instance of ``django.template.loader.LoaderOrigin`` or
  612. ``django.template.base.StringOrigin`` was set as the origin attribute on the
  613. template object. These classes have been combined into
  614. :class:`~django.template.base.Origin` and is now always set regardless of the
  615. engine debug setting. For a minimal level of backwards compatibility, the old
  616. class names will be kept as aliases to the new ``Origin`` class until
  617. Django 2.0.
  618. .. _default-logging-changes-19:
  619. Changes to the default logging configuration
  620. --------------------------------------------
  621. To make it easier to write custom logging configurations, Django's default
  622. logging configuration no longer defines ``django.request`` and
  623. ``django.security`` loggers. Instead, it defines a single ``django`` logger,
  624. filtered at the ``INFO`` level, with two handlers:
  625. * ``console``: filtered at the ``INFO`` level and only active if ``DEBUG=True``.
  626. * ``mail_admins``: filtered at the ``ERROR`` level and only active if
  627. ``DEBUG=False``.
  628. If you aren't overriding Django's default logging, you should see minimal
  629. changes in behavior, but you might see some new logging to the ``runserver``
  630. console, for example.
  631. If you are overriding Django's default logging, you should check to see how
  632. your configuration merges with the new defaults.
  633. ``HttpRequest`` details in error reporting
  634. ------------------------------------------
  635. It was redundant to display the full details of the
  636. :class:`~django.http.HttpRequest` each time it appeared as a stack frame
  637. variable in the HTML version of the debug page and error email. Thus, the HTTP
  638. request will now display the same standard representation as other variables
  639. (``repr(request)``). As a result, the
  640. ``ExceptionReporterFilter.get_request_repr()`` method and the undocumented
  641. ``django.http.build_request_repr()`` function were removed.
  642. The contents of the text version of the email were modified to provide a
  643. traceback of the same structure as in the case of AJAX requests. The traceback
  644. details are rendered by the ``ExceptionReporter.get_traceback_text()`` method.
  645. Removal of time zone aware global adapters and converters for datetimes
  646. -----------------------------------------------------------------------
  647. Django no longer registers global adapters and converters for managing time
  648. zone information on :class:`~datetime.datetime` values sent to the database as
  649. query parameters or read from the database in query results. This change
  650. affects projects that meet all the following conditions:
  651. * The :setting:`USE_TZ` setting is ``True``.
  652. * The database is SQLite, MySQL, Oracle, or a third-party database that
  653. doesn't support time zones. In doubt, you can check the value of
  654. ``connection.features.supports_timezones``.
  655. * The code queries the database outside of the ORM, typically with
  656. ``cursor.execute(sql, params)``.
  657. If you're passing aware :class:`~datetime.datetime` parameters to such
  658. queries, you should turn them into naive datetimes in UTC::
  659. from django.utils import timezone
  660. param = timezone.make_naive(param, timezone.utc)
  661. If you fail to do so, the conversion will be performed as in earlier versions
  662. (with a deprecation warning) up until Django 1.11. Django 2.0 won't perform any
  663. conversion, which may result in data corruption.
  664. If you're reading :class:`~datetime.datetime` values from the results, they
  665. will be naive instead of aware. You can compensate as follows::
  666. from django.utils import timezone
  667. value = timezone.make_aware(value, timezone.utc)
  668. You don't need any of this if you're querying the database through the ORM,
  669. even if you're using :meth:`raw() <django.db.models.query.QuerySet.raw>`
  670. queries. The ORM takes care of managing time zone information.
  671. Template tag modules are imported when templates are configured
  672. ---------------------------------------------------------------
  673. The :class:`~django.template.backends.django.DjangoTemplates` backend now
  674. performs discovery on installed template tag modules when instantiated. This
  675. update enables libraries to be provided explicitly via the ``'libraries'``
  676. key of :setting:`OPTIONS <TEMPLATES-OPTIONS>` when defining a
  677. :class:`~django.template.backends.django.DjangoTemplates` backend. Import
  678. or syntax errors in template tag modules now fail early at instantiation time
  679. rather than when a template with a :ttag:`{% load %}<load>` tag is first
  680. compiled.
  681. ``django.template.base.add_to_builtins()`` is removed
  682. -----------------------------------------------------
  683. Although it was a private API, projects commonly used ``add_to_builtins()`` to
  684. make template tags and filters available without using the
  685. :ttag:`{% load %}<load>` tag. This API has been formalized. Projects should now
  686. define built-in libraries via the ``'builtins'`` key of :setting:`OPTIONS
  687. <TEMPLATES-OPTIONS>` when defining a
  688. :class:`~django.template.backends.django.DjangoTemplates` backend.
  689. .. _simple-tag-conditional-escape-fix:
  690. ``simple_tag`` now wraps tag output in ``conditional_escape``
  691. -------------------------------------------------------------
  692. In general, template tags do not autoescape their contents, and this behavior is
  693. :ref:`documented <tags-auto-escaping>`. For tags like
  694. :class:`~django.template.Library.inclusion_tag`, this is not a problem because
  695. the included template will perform autoescaping. For ``assignment_tag()``,
  696. the output will be escaped when it is used as a variable in the template.
  697. For the intended use cases of :class:`~django.template.Library.simple_tag`,
  698. however, it is very easy to end up with incorrect HTML and possibly an XSS
  699. exploit. For example::
  700. @register.simple_tag(takes_context=True)
  701. def greeting(context):
  702. return "Hello {0}!".format(context["request"].user.first_name)
  703. In older versions of Django, this will be an XSS issue because
  704. ``user.first_name`` is not escaped.
  705. In Django 1.9, this is fixed: if the template context has ``autoescape=True``
  706. set (the default), then ``simple_tag`` will wrap the output of the tag function
  707. with :func:`~django.utils.html.conditional_escape`.
  708. To fix your ``simple_tag``\s, it is best to apply the following practices:
  709. * Any code that generates HTML should use either the template system or
  710. :func:`~django.utils.html.format_html`.
  711. * If the output of a ``simple_tag`` needs escaping, use
  712. :func:`~django.utils.html.escape` or
  713. :func:`~django.utils.html.conditional_escape`.
  714. * If you are absolutely certain that you are outputting HTML from a trusted
  715. source (e.g. a CMS field that stores HTML entered by admins), you can mark it
  716. as such using :func:`~django.utils.safestring.mark_safe`.
  717. Tags that follow these rules will be correct and safe whether they are run on
  718. Django 1.9+ or earlier.
  719. ``Paginator.page_range``
  720. ------------------------
  721. :attr:`Paginator.page_range <django.core.paginator.Paginator.page_range>` is
  722. now an iterator instead of a list.
  723. In versions of Django previous to 1.8, ``Paginator.page_range`` returned a
  724. ``list`` in Python 2 and a ``range`` in Python 3. Django 1.8 consistently
  725. returned a list, but an iterator is more efficient.
  726. Existing code that depends on ``list`` specific features, such as indexing,
  727. can be ported by converting the iterator into a ``list`` using ``list()``.
  728. Implicit ``QuerySet`` ``__in`` lookup removed
  729. ---------------------------------------------
  730. In earlier versions, queries such as::
  731. Model.objects.filter(related_id=RelatedModel.objects.all())
  732. would implicitly convert to::
  733. Model.objects.filter(related_id__in=RelatedModel.objects.all())
  734. resulting in SQL like ``"related_id IN (SELECT id FROM ...)"``.
  735. This implicit ``__in`` no longer happens so the "IN" SQL is now "=", and if the
  736. subquery returns multiple results, at least some databases will throw an error.
  737. .. _admin-browser-support-19:
  738. ``contrib.admin`` browser support
  739. ---------------------------------
  740. The admin no longer supports Internet Explorer 8 and below, as these browsers
  741. have reached end-of-life.
  742. CSS and images to support Internet Explorer 6 and 7 have been removed. PNG and
  743. GIF icons have been replaced with SVG icons, which are not supported by
  744. Internet Explorer 8 and earlier.
  745. The jQuery library embedded in the admin has been upgraded from version 1.11.2
  746. to 2.1.4. jQuery 2.x has the same API as jQuery 1.x, but does not support
  747. Internet Explorer 6, 7, or 8, allowing for better performance and a smaller
  748. file size. If you need to support IE8 and must also use the latest version of
  749. Django, you can override the admin's copy of jQuery with your own by creating
  750. a Django application with this structure:
  751. .. code-block:: text
  752. app/static/admin/js/vendor/
  753. jquery.js
  754. jquery.min.js
  755. .. _syntax-error-old-setuptools-django-19:
  756. ``SyntaxError`` when installing Django ``setuptools`` 5.5.x
  757. -----------------------------------------------------------
  758. When installing Django 1.9 or 1.9.1 with ``setuptools`` 5.5.x, you'll see:
  759. .. code-block:: shell
  760. Compiling django/conf/app_template/apps.py ...
  761. File "django/conf/app_template/apps.py", line 4
  762. class {{ camel_case_app_name }}Config(AppConfig):
  763. ^
  764. SyntaxError: invalid syntax
  765. Compiling django/conf/app_template/models.py ...
  766. File "django/conf/app_template/models.py", line 1
  767. {{ unicode_literals }}from django.db import models
  768. ^
  769. SyntaxError: invalid syntax
  770. It's safe to ignore these errors (Django will still install just fine), but you
  771. can avoid them by upgrading ``setuptools`` to a more recent version. If you're
  772. using pip, you can upgrade pip using ``python -m pip install -U pip`` which
  773. will also upgrade ``setuptools``. This is resolved in later versions of Django
  774. as described in the :doc:`/releases/1.9.2`.
  775. Miscellaneous
  776. -------------
  777. * The jQuery static files in ``contrib.admin`` have been moved into a
  778. ``vendor/jquery`` subdirectory.
  779. * The text displayed for null columns in the admin changelist ``list_display``
  780. cells has changed from ``(None)`` (or its translated equivalent) to ``-`` (a
  781. dash).
  782. * ``django.http.responses.REASON_PHRASES`` and
  783. ``django.core.handlers.wsgi.STATUS_CODE_TEXT`` have been removed. Use
  784. Python's Standard Library instead: :data:`http.client.responses` for Python
  785. 3 and `httplib.responses`_ for Python 2.
  786. .. _`httplib.responses`: https://docs.python.org/2/library/httplib.html#httplib.responses
  787. * ``ValuesQuerySet`` and ``ValuesListQuerySet`` have been removed.
  788. * The ``admin/base.html`` template no longer sets
  789. ``window.__admin_media_prefix__`` or ``window.__admin_utc_offset__``. Image
  790. references in JavaScript that used that value to construct absolute URLs have
  791. been moved to CSS for easier customization. The UTC offset is stored on a
  792. data attribute of the ``<body>`` tag.
  793. * ``CommaSeparatedIntegerField`` validation has been refined to forbid values
  794. like ``','``, ``',1'``, and ``'1,,2'``.
  795. * Form initialization was moved from the :meth:`ProcessFormView.get()
  796. <django.views.generic.edit.ProcessFormView.get>` method to the new
  797. :meth:`FormMixin.get_context_data()
  798. <django.views.generic.edit.FormMixin.get_context_data>` method. This may be
  799. backwards incompatible if you have overridden the ``get_context_data()``
  800. method without calling ``super()``.
  801. * Support for PostGIS 1.5 has been dropped.
  802. * The ``django.contrib.sites.models.Site.domain`` field was changed to be
  803. :attr:`~django.db.models.Field.unique`.
  804. * In order to enforce test isolation, database queries are not allowed
  805. by default in :class:`~django.test.SimpleTestCase` tests anymore. You
  806. can disable this behavior by setting the ``allow_database_queries`` class
  807. attribute to ``True`` on your test class.
  808. * ``ResolverMatch.app_name`` was changed to contain the full namespace path in
  809. the case of nested namespaces. For consistency with
  810. ``ResolverMatch.namespace``, the empty value is now an empty string instead
  811. of ``None``.
  812. * For security hardening, session keys must be at least 8 characters.
  813. * Private function ``django.utils.functional.total_ordering()`` has been
  814. removed. It contained a workaround for a ``functools.total_ordering()`` bug
  815. in Python versions older than 2.7.3.
  816. * XML serialization (either through :djadmin:`dumpdata` or the syndication
  817. framework) used to output any characters it received. Now if the content to
  818. be serialized contains any control characters not allowed in the XML 1.0
  819. standard, the serialization will fail with a :exc:`ValueError`.
  820. * :class:`~django.forms.CharField` now strips input of leading and trailing
  821. whitespace by default. This can be disabled by setting the new
  822. :attr:`~django.forms.CharField.strip` argument to ``False``.
  823. * Template text that is translated and uses two or more consecutive percent
  824. signs, e.g. ``"%%"``, may have a new ``msgid`` after ``makemessages`` is run
  825. (most likely the translation will be marked fuzzy). The new ``msgid`` will be
  826. marked ``"#, python-format"``.
  827. * If neither :attr:`request.current_app <django.http.HttpRequest.current_app>`
  828. nor :class:`Context.current_app <django.template.Context>` are set, the
  829. :ttag:`url` template tag will now use the namespace of the current request.
  830. Set ``request.current_app`` to ``None`` if you don't want to use a namespace
  831. hint.
  832. * The :setting:`SILENCED_SYSTEM_CHECKS` setting now silences messages of all
  833. levels. Previously, messages of ``ERROR`` level or higher were printed to the
  834. console.
  835. * The ``FlatPage.enable_comments`` field is removed from the ``FlatPageAdmin``
  836. as it's unused by the application. If your project or a third-party app makes
  837. use of it, :ref:`create a custom ModelAdmin <flatpages-admin>` to add it back.
  838. * The return value of
  839. :meth:`~django.test.runner.DiscoverRunner.setup_databases` and the first
  840. argument of :meth:`~django.test.runner.DiscoverRunner.teardown_databases`
  841. changed. They used to be ``(old_names, mirrors)`` tuples. Now they're just
  842. the first item, ``old_names``.
  843. * By default :class:`~django.test.LiveServerTestCase` attempts to find an
  844. available port in the 8081-8179 range instead of just trying port 8081.
  845. * The system checks for :class:`~django.contrib.admin.ModelAdmin` now check
  846. instances rather than classes.
  847. * The private API to apply mixed migration plans has been dropped for
  848. performance reasons. Mixed plans consist of a list of migrations where some
  849. are being applied and others are being unapplied.
  850. * The related model object descriptor classes in
  851. ``django.db.models.fields.related`` (private API) are moved from the
  852. ``related`` module to ``related_descriptors`` and renamed as follows:
  853. * ``ReverseSingleRelatedObjectDescriptor`` is ``ForwardManyToOneDescriptor``
  854. * ``SingleRelatedObjectDescriptor`` is ``ReverseOneToOneDescriptor``
  855. * ``ForeignRelatedObjectsDescriptor`` is ``ReverseManyToOneDescriptor``
  856. * ``ManyRelatedObjectsDescriptor`` is ``ManyToManyDescriptor``
  857. * If you implement a custom :data:`~django.conf.urls.handler404` view, it must
  858. return a response with an HTTP 404 status code. Use
  859. :class:`~django.http.HttpResponseNotFound` or pass ``status=404`` to the
  860. :class:`~django.http.HttpResponse`. Otherwise, :setting:`APPEND_SLASH` won't
  861. work correctly with ``DEBUG=False``.
  862. .. _deprecated-features-1.9:
  863. Features deprecated in 1.9
  864. ==========================
  865. ``assignment_tag()``
  866. --------------------
  867. Django 1.4 added the ``assignment_tag`` helper to ease the creation of
  868. template tags that store results in a template variable. The
  869. :meth:`~django.template.Library.simple_tag` helper has gained this same
  870. ability, making the ``assignment_tag`` obsolete. Tags that use
  871. ``assignment_tag`` should be updated to use ``simple_tag``.
  872. ``{% cycle %}`` syntax with comma-separated arguments
  873. -----------------------------------------------------
  874. The :ttag:`cycle` tag supports an inferior old syntax from previous Django
  875. versions:
  876. .. code-block:: html+django
  877. {% cycle row1,row2,row3 %}
  878. Its parsing caused bugs with the current syntax, so support for the old syntax
  879. will be removed in Django 1.10 following an accelerated deprecation.
  880. ``ForeignKey`` and ``OneToOneField`` ``on_delete`` argument
  881. -----------------------------------------------------------
  882. In order to increase awareness about cascading model deletion, the
  883. ``on_delete`` argument of ``ForeignKey`` and ``OneToOneField`` will be required
  884. in Django 2.0.
  885. Update models and existing migrations to explicitly set the argument. Since the
  886. default is ``models.CASCADE``, add ``on_delete=models.CASCADE`` to all
  887. ``ForeignKey`` and ``OneToOneField``\s that don't use a different option. You
  888. can also pass it as the second positional argument if you don't care about
  889. compatibility with older versions of Django.
  890. ``Field.rel`` changes
  891. ---------------------
  892. ``Field.rel`` and its methods and attributes have changed to match the related
  893. fields API. The ``Field.rel`` attribute is renamed to ``remote_field`` and many
  894. of its methods and attributes are either changed or renamed.
  895. The aim of these changes is to provide a documented API for relation fields.
  896. ``GeoManager`` and ``GeoQuerySet`` custom methods
  897. -------------------------------------------------
  898. All custom ``GeoQuerySet`` methods (``area()``, ``distance()``, ``gml()``, ...)
  899. have been replaced by equivalent geographic expressions in annotations (see in
  900. new features). Hence the need to set a custom ``GeoManager`` to GIS-enabled
  901. models is now obsolete. As soon as your code doesn't call any of the deprecated
  902. methods, you can simply remove the ``objects = GeoManager()`` lines from your
  903. models.
  904. Template loader APIs have changed
  905. ---------------------------------
  906. Django template loaders have been updated to allow recursive template
  907. extending. This change necessitated a new template loader API. The old
  908. ``load_template()`` and ``load_template_sources()`` methods are now deprecated.
  909. Details about the new API can be found :ref:`in the template loader
  910. documentation <custom-template-loaders>`.
  911. Passing a 3-tuple or an ``app_name`` to ``include()``
  912. -----------------------------------------------------
  913. The instance namespace part of passing a tuple as an argument to ``include()``
  914. has been replaced by passing the ``namespace`` argument to ``include()``. For
  915. example::
  916. polls_patterns = [
  917. url(...),
  918. ]
  919. urlpatterns = [
  920. url(r"^polls/", include((polls_patterns, "polls", "author-polls"))),
  921. ]
  922. becomes::
  923. polls_patterns = (
  924. [
  925. url(...),
  926. ],
  927. "polls",
  928. ) # 'polls' is the app_name
  929. urlpatterns = [
  930. url(r"^polls/", include(polls_patterns, namespace="author-polls")),
  931. ]
  932. The ``app_name`` argument to ``include()`` has been replaced by passing a
  933. 2-tuple (as above), or passing an object or module with an ``app_name``
  934. attribute (as below). If the ``app_name`` is set in this new way, the
  935. ``namespace`` argument is no longer required. It will default to the value of
  936. ``app_name``. For example, the URL patterns in the tutorial are changed from:
  937. .. code-block:: python
  938. :caption: ``mysite/urls.py``
  939. urlpatterns = [url(r"^polls/", include("polls.urls", namespace="polls")), ...]
  940. to:
  941. .. code-block:: python
  942. :caption: ``mysite/urls.py``
  943. urlpatterns = [
  944. url(r"^polls/", include("polls.urls")), # 'namespace="polls"' removed
  945. ...,
  946. ]
  947. .. code-block:: python
  948. :caption: ``polls/urls.py``
  949. app_name = "polls" # added
  950. urlpatterns = [...]
  951. This change also means that the old way of including an ``AdminSite`` instance
  952. is deprecated. Instead, pass ``admin.site.urls`` directly to
  953. ``django.conf.urls.url()``:
  954. .. code-block:: python
  955. :caption: ``urls.py``
  956. from django.conf.urls import url
  957. from django.contrib import admin
  958. urlpatterns = [
  959. url(r"^admin/", admin.site.urls),
  960. ]
  961. URL application namespace required if setting an instance namespace
  962. -------------------------------------------------------------------
  963. In the past, an instance namespace without an application namespace
  964. would serve the same purpose as the application namespace, but it was
  965. impossible to reverse the patterns if there was an application namespace
  966. with the same name. Includes that specify an instance namespace require that
  967. the included URLconf sets an application namespace.
  968. ``current_app`` parameter to ``contrib.auth`` views
  969. ---------------------------------------------------
  970. All views in ``django.contrib.auth.views`` have the following structure:
  971. .. code-block:: text
  972. def view(request, ..., current_app=None, ...):
  973. ...
  974. if current_app is not None:
  975. request.current_app = current_app
  976. return TemplateResponse(request, template_name, context)
  977. As of Django 1.8, ``current_app`` is set on the ``request`` object. For
  978. consistency, these views will require the caller to set ``current_app`` on the
  979. ``request`` instead of passing it in a separate argument.
  980. ``django.contrib.gis.geoip``
  981. ----------------------------
  982. The :mod:`django.contrib.gis.geoip2` module supersedes
  983. ``django.contrib.gis.geoip``. The new module provides a similar API except that
  984. it doesn't provide the legacy GeoIP-Python API compatibility methods.
  985. Miscellaneous
  986. -------------
  987. * The ``weak`` argument to ``django.dispatch.signals.Signal.disconnect()`` has
  988. been deprecated as it has no effect.
  989. * The ``check_aggregate_support()`` method of
  990. ``django.db.backends.base.BaseDatabaseOperations`` has been deprecated and
  991. will be removed in Django 2.0. The more general ``check_expression_support()``
  992. should be used instead.
  993. * ``django.forms.extras`` is deprecated. You can find
  994. :class:`~django.forms.SelectDateWidget` in ``django.forms.widgets``
  995. (or simply ``django.forms``) instead.
  996. * Private API ``django.db.models.fields.add_lazy_relation()`` is deprecated.
  997. * The ``django.contrib.auth.tests.utils.skipIfCustomUser()`` decorator is
  998. deprecated. With the test discovery changes in Django 1.6, the tests for
  999. ``django.contrib`` apps are no longer run as part of the user's project.
  1000. Therefore, the ``@skipIfCustomUser`` decorator is no longer needed to
  1001. decorate tests in ``django.contrib.auth``.
  1002. * If you customized some :ref:`error handlers <error-views>`, the view
  1003. signatures with only one request parameter are deprecated. The views should
  1004. now also accept a second ``exception`` positional parameter.
  1005. * The ``django.utils.feedgenerator.Atom1Feed.mime_type`` and
  1006. ``django.utils.feedgenerator.RssFeed.mime_type`` attributes are deprecated in
  1007. favor of ``content_type``.
  1008. * :class:`~django.core.signing.Signer` now issues a warning if an invalid
  1009. separator is used. This will become an exception in Django 1.10.
  1010. * ``django.db.models.Field._get_val_from_obj()`` is deprecated in favor of
  1011. ``Field.value_from_object()``.
  1012. * ``django.template.loaders.eggs.Loader`` is deprecated as distributing
  1013. applications as eggs is not recommended.
  1014. * The ``callable_obj`` keyword argument to
  1015. ``SimpleTestCase.assertRaisesMessage()`` is deprecated. Pass the callable as
  1016. a positional argument instead.
  1017. * The ``allow_tags`` attribute on methods of ``ModelAdmin`` has been
  1018. deprecated. Use :func:`~django.utils.html.format_html`,
  1019. :func:`~django.utils.html.format_html_join`, or
  1020. :func:`~django.utils.safestring.mark_safe` when constructing the method's
  1021. return value instead.
  1022. * The ``enclosure`` keyword argument to ``SyndicationFeed.add_item()`` is
  1023. deprecated. Use the new ``enclosures`` argument which accepts a list of
  1024. ``Enclosure`` objects instead of a single one.
  1025. * The ``django.template.loader.LoaderOrigin`` and
  1026. ``django.template.base.StringOrigin`` aliases for
  1027. ``django.template.base.Origin`` are deprecated.
  1028. .. _removed-features-1.9:
  1029. Features removed in 1.9
  1030. =======================
  1031. These features have reached the end of their deprecation cycle and are removed
  1032. in Django 1.9. See :ref:`deprecated-features-1.7` for details, including how to
  1033. remove usage of these features.
  1034. * ``django.utils.dictconfig`` is removed.
  1035. * ``django.utils.importlib`` is removed.
  1036. * ``django.utils.tzinfo`` is removed.
  1037. * ``django.utils.unittest`` is removed.
  1038. * The ``syncdb`` command is removed.
  1039. * ``django.db.models.signals.pre_syncdb`` and
  1040. ``django.db.models.signals.post_syncdb`` is removed.
  1041. * Support for ``allow_syncdb`` on database routers is removed.
  1042. * Automatic syncing of apps without migrations is removed. Migrations are
  1043. compulsory for all apps unless you pass the :option:`migrate --run-syncdb`
  1044. option.
  1045. * The SQL management commands for apps without migrations, ``sql``, ``sqlall``,
  1046. ``sqlclear``, ``sqldropindexes``, and ``sqlindexes``, are removed.
  1047. * Support for automatic loading of ``initial_data`` fixtures and initial SQL
  1048. data is removed.
  1049. * All models need to be defined inside an installed application or declare an
  1050. explicit :attr:`~django.db.models.Options.app_label`. Furthermore, it isn't
  1051. possible to import them before their application is loaded. In particular, it
  1052. isn't possible to import models inside the root package of an application.
  1053. * The model and form ``IPAddressField`` is removed. A stub field remains for
  1054. compatibility with historical migrations.
  1055. * ``AppCommand.handle_app()`` is no longer supported.
  1056. * ``RequestSite`` and ``get_current_site()`` are no longer importable from
  1057. ``django.contrib.sites.models``.
  1058. * FastCGI support via the ``runfcgi`` management command is removed.
  1059. * ``django.utils.datastructures.SortedDict`` is removed.
  1060. * ``ModelAdmin.declared_fieldsets`` is removed.
  1061. * The ``util`` modules that provided backwards compatibility are removed:
  1062. * ``django.contrib.admin.util``
  1063. * ``django.contrib.gis.db.backends.util``
  1064. * ``django.db.backends.util``
  1065. * ``django.forms.util``
  1066. * ``ModelAdmin.get_formsets`` is removed.
  1067. * The backward compatible shims introduced to rename the
  1068. ``BaseMemcachedCache._get_memcache_timeout()`` method to
  1069. ``get_backend_timeout()`` is removed.
  1070. * The ``--natural`` and ``-n`` options for :djadmin:`dumpdata` are removed.
  1071. * The ``use_natural_keys`` argument for ``serializers.serialize()`` is removed.
  1072. * Private API ``django.forms.forms.get_declared_fields()`` is removed.
  1073. * The ability to use a ``SplitDateTimeWidget`` with ``DateTimeField`` is
  1074. removed.
  1075. * The ``WSGIRequest.REQUEST`` property is removed.
  1076. * The class ``django.utils.datastructures.MergeDict`` is removed.
  1077. * The ``zh-cn`` and ``zh-tw`` language codes are removed.
  1078. * The internal ``django.utils.functional.memoize()`` is removed.
  1079. * ``django.core.cache.get_cache`` is removed.
  1080. * ``django.db.models.loading`` is removed.
  1081. * Passing callable arguments to querysets is no longer possible.
  1082. * ``BaseCommand.requires_model_validation`` is removed in favor of
  1083. ``requires_system_checks``. Admin validators is replaced by admin checks.
  1084. * The ``ModelAdmin.validator_class`` and ``default_validator_class`` attributes
  1085. are removed.
  1086. * ``ModelAdmin.validate()`` is removed.
  1087. * ``django.db.backends.DatabaseValidation.validate_field`` is removed in
  1088. favor of the ``check_field`` method.
  1089. * The ``validate`` management command is removed.
  1090. * ``django.utils.module_loading.import_by_path`` is removed in favor of
  1091. ``django.utils.module_loading.import_string``.
  1092. * ``ssi`` and ``url`` template tags are removed from the ``future`` template
  1093. tag library.
  1094. * ``django.utils.text.javascript_quote()`` is removed.
  1095. * Database test settings as independent entries in the database settings,
  1096. prefixed by ``TEST_``, are no longer supported.
  1097. * The ``cache_choices`` option to :class:`~django.forms.ModelChoiceField` and
  1098. :class:`~django.forms.ModelMultipleChoiceField` is removed.
  1099. * The default value of the
  1100. :attr:`RedirectView.permanent <django.views.generic.base.RedirectView.permanent>`
  1101. attribute has changed from ``True`` to ``False``.
  1102. * ``django.contrib.sitemaps.FlatPageSitemap`` is removed in favor of
  1103. ``django.contrib.flatpages.sitemaps.FlatPageSitemap``.
  1104. * Private API ``django.test.utils.TestTemplateLoader`` is removed.
  1105. * The ``django.contrib.contenttypes.generic`` module is removed.