Debian Codegraph @

docs/releases/1.6.txt

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