Debian Codegraph @

docs/releases/1.9.txt

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