-
-
Notifications
You must be signed in to change notification settings - Fork 31.1k
/
1.8.txt
1670 lines (1237 loc) · 70 KB
/
1.8.txt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
============================================
Django 1.8 release notes - UNDER DEVELOPMENT
============================================
Welcome to Django 1.8!
These release notes cover the `new features`_, as well as some `backwards
incompatible changes`_ you'll want to be aware of when upgrading from Django
1.7 or older versions. We've also `begun the deprecation process for some
features`_, and some features have reached the end of their deprecation process
and `have been removed`_.
Django 1.8 has been designated as Django's second :ref:`"Long-Term Support"
(LTS) <lts-releases>` release. It will receive security updates for at least
three years after its release. Support for the previous LTS, Django 1.4, will
end 6 months from the release date of Django 1.8.
.. _`new features`: `What's new in Django 1.8`_
.. _`backwards incompatible changes`: `Backwards incompatible changes in 1.8`_
.. _`begun the deprecation process for some features`: `Features deprecated in 1.8`_
.. _`have been removed`: `Features removed in 1.8`_
Python compatibility
====================
Like Django 1.7, Django 1.8 requires Python 2.7 or above, though we
**highly recommend** the latest minor release.
What's new in Django 1.8
========================
``Model._meta`` API
~~~~~~~~~~~~~~~~~~~
Django now has a formalized API for :doc:`Model._meta </ref/models/meta>`,
providing an officially supported way to :ref:`retrieve fields
<model-meta-field-api>` and filter fields based on their :ref:`attributes
<model-field-attributes>`.
The ``Model._meta`` object has been part of Django since the days of pre-0.96
"Magic Removal" -- it just wasn't an official, stable API. In recognition of
this, we've endeavored to maintain backwards-compatibility with the old
API endpoint where possible. However, API endpoints that aren't part of the
new official API have been deprecated and will eventually be removed. A
:ref:`guide to migrating from the old API to the new API
<migrating-old-meta-api>` has been provided.
Multiple template engines
~~~~~~~~~~~~~~~~~~~~~~~~~
Django 1.8 defines a stable API for integrating template backends. It includes
built-in support for the Django template language and for Jinja2_. It supports
rendering templates with multiple engines within the same project. Learn more
about the new features in the :doc:`topic guide </topics/templates>` and check
the :doc:`upgrade instructions </ref/templates/upgrading>` for details.
.. _Jinja2: http://jinja.pocoo.org/
Security enhancements
~~~~~~~~~~~~~~~~~~~~~
Several features of the django-secure_ third-party library have been
integrated into Django. :class:`django.middleware.security.SecurityMiddleware`
provides several security enhancements to the request/response cycle. The new
:djadminopt:`--deploy` option of the :djadmin:`check` command allows you to
check your production settings file for ways to increase the security of your
site.
.. _django-secure: https://pypi.python.org/pypi/django-secure
New PostgreSQL specific functionality
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Django now has a module with extensions for PostgreSQL specific features, such
as :class:`~django.contrib.postgres.fields.ArrayField`,
:class:`~django.contrib.postgres.fields.HStoreField`, :ref:`range-fields`, and
:lookup:`unaccent` lookup. A full breakdown of the features is available
:doc:`in the documentation </ref/contrib/postgres/index>`.
New data types
~~~~~~~~~~~~~~
* Django now has a :class:`~django.db.models.UUIDField` for storing
universally unique identifiers. It is stored as the native ``uuid`` data type
on PostgreSQL and as a fixed length character field on other backends. There
is a corresponding :class:`form field <django.forms.UUIDField>`.
* Django now has a :class:`~django.db.models.DurationField` for storing periods
of time - modeled in Python by :class:`~python:datetime.timedelta`. It is
stored in the native ``interval`` data type on PostgreSQL, as a ``INTERVAL
DAY(9) TO SECOND(6)`` on Oracle, and as a ``bigint`` of microseconds on other
backends. Date and time related arithmetic has also been improved on all
backends. There is a corresponding :class:`form field
<django.forms.DurationField>`.
Query Expressions, Conditional Expressions, and Database Functions
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:doc:`Query Expressions </ref/models/expressions>` allow you to create,
customize, and compose complex SQL expressions. This has enabled annotate
to accept expressions other than aggregates. Aggregates are now able to
reference multiple fields, as well as perform arithmetic, similar to ``F()``
objects. :meth:`~django.db.models.query.QuerySet.order_by` has also gained the
ability to accept expressions.
:doc:`Conditional Expressions </ref/models/conditional-expressions>` allow
you to use :keyword:`if` ... :keyword:`elif` ... :keyword:`else` logic within
queries.
A collection of :doc:`database functions </ref/models/database-functions>` is
also included with functionality such as
:class:`~django.db.models.functions.Coalesce`,
:class:`~django.db.models.functions.Concat`, and
:class:`~django.db.models.functions.Substr`.
``TestCase`` data setup
~~~~~~~~~~~~~~~~~~~~~~~
:class:`~django.test.TestCase` has been refactored to allow for data
initialization at the class level using transactions and savepoints. Database
backends which do not support transactions, like MySQL with the MyISAM storage
engine, will still be able to run these tests but won't benefit from the
improvements. Tests are now run within two nested
:func:`~django.db.transaction.atomic()` blocks: one for the whole class and one
for each test.
* The class method
:meth:`TestCase.setUpTestData() <django.test.TestCase.setUpTestData>` adds
the ability to setup test data at the class level. Using this technique can
speed up the tests as compared to using ``setUp()``.
* Fixture loading within ``TestCase`` is now performed once for the whole
``TestCase``.
Minor features
~~~~~~~~~~~~~~
:mod:`django.contrib.admin`
^^^^^^^^^^^^^^^^^^^^^^^^^^^
* :class:`~django.contrib.admin.ModelAdmin` now has a
:meth:`~django.contrib.admin.ModelAdmin.has_module_permission`
method to allow limiting access to the module on the admin index page.
* :class:`~django.contrib.admin.InlineModelAdmin` now has an attribute
:attr:`~django.contrib.admin.InlineModelAdmin.show_change_link` that
supports showing a link to an inline object's change form.
* Use the new ``django.contrib.admin.RelatedOnlyFieldListFilter`` in
:attr:`ModelAdmin.list_filter <django.contrib.admin.ModelAdmin.list_filter>`
to limit the ``list_filter`` choices to foreign objects which are attached to
those from the ``ModelAdmin``.
* The :meth:`ModelAdmin.delete_view()
<django.contrib.admin.ModelAdmin.delete_view>` displays a summary of objects
to be deleted on the deletion confirmation page.
* The jQuery library embedded in the admin has been upgraded to version 1.11.2.
* You can now specify :attr:`AdminSite.site_url
<django.contrib.admin.AdminSite.site_url>` in order to display a link to the
front-end site.
* You can now specify :attr:`ModelAdmin.show_full_result_count
<django.contrib.admin.ModelAdmin.show_full_result_count>` to control whether
or not the full count of objects should be displayed on a filtered admin page.
* The ``AdminSite.password_change()`` method now has an ``extra_context``
parameter.
* You can now control who may login to the admin site by overriding only
:meth:`AdminSite.has_permission()
<django.contrib.admin.AdminSite.has_permission>` and
:attr:`AdminSite.login_form <django.contrib.admin.AdminSite.login_form>`.
The ``base.html`` template has a new block ``usertools`` which contains the
user-specific header. A new context variable ``has_permission``, which gets
its value from :meth:`~django.contrib.admin.AdminSite.has_permission`,
indicates whether the user may access the site.
* Foreign key dropdowns now have buttons for changing or deleting related
objects using a popup.
:mod:`django.contrib.admindocs`
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
* reStructuredText is now parsed in model docstrings.
:mod:`django.contrib.auth`
^^^^^^^^^^^^^^^^^^^^^^^^^^
* Authorization backends can now raise
:class:`~django.core.exceptions.PermissionDenied` in
:meth:`~django.contrib.auth.models.User.has_perm`
and :meth:`~django.contrib.auth.models.User.has_module_perms`
to short-circuit permission checking.
* :class:`~django.contrib.auth.forms.PasswordResetForm` now
has a method :meth:`~django.contrib.auth.forms.PasswordResetForm.send_email`
that can be overridden to customize the mail to be sent.
* The ``max_length`` of :attr:`Permission.name
<django.contrib.auth.models.Permission.name>` has been increased from 50 to
255 characters. Please run the database migration.
* :attr:`~django.contrib.auth.models.CustomUser.USERNAME_FIELD` and
:attr:`~django.contrib.auth.models.CustomUser.REQUIRED_FIELDS` now supports
:class:`~django.db.models.ForeignKey`\s.
* The default iteration count for the PBKDF2 password hasher has been
increased by 33%. This backwards compatible change will not affect users who
have subclassed ``django.contrib.auth.hashers.PBKDF2PasswordHasher`` to
change the default value.
:mod:`django.contrib.gis`
^^^^^^^^^^^^^^^^^^^^^^^^^^
* A new :doc:`GeoJSON serializer </ref/contrib/gis/serializers>` is now
available.
* The Spatialite backend now supports ``Collect`` and ``Extent`` aggregates
when the database version is 3.0 or later.
* The PostGIS 2 ``CREATE EXTENSION postgis`` and the Spatialite
``SELECT InitSpatialMetaData`` initialization commands are now automatically
run by :djadmin:`migrate`.
* The GDAL interface now supports retrieving properties of
:ref:`raster (image) data file <raster-data-source-objects>`.
* Compatibility shims for ``SpatialRefSys`` and ``GeometryColumns`` changed in
Django 1.2 have been removed.
* All GDAL-related exceptions are now raised with ``GDALException``. The former
``OGRException`` has been kept for backwards compatibility but should not be
used any longer.
:mod:`django.contrib.messages`
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
* ...
:mod:`django.contrib.redirects`
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
* ...
:mod:`django.contrib.sessions`
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
* Session cookie is now deleted after
:meth:`~django.contrib.sessions.backends.base.SessionBase.flush()` is called.
:mod:`django.contrib.sitemaps`
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
* The new :attr:`Sitemap.i18n <django.contrib.sitemaps.Sitemap.i18n>` attribute
allows you to generate a sitemap based on the :setting:`LANGUAGES` setting.
:mod:`django.contrib.sites`
^^^^^^^^^^^^^^^^^^^^^^^^^^^
* :func:`~django.contrib.sites.shortcuts.get_current_site` will now lookup
the current site based on :meth:`request.get_host()
<django.http.HttpRequest.get_host>` if the :setting:`SITE_ID` setting is not
defined.
* The default :class:`~django.contrib.sites.models.Site` created when running
``migrate`` now respects the :setting:`SITE_ID` setting (instead of always
using ``pk=1``).
:mod:`django.contrib.staticfiles`
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
* ...
:mod:`django.contrib.syndication`
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
* ...
Cache
^^^^^
* The ``incr()`` method of the
``django.core.cache.backends.locmem.LocMemCache`` backend is now thread-safe.
Cryptography
^^^^^^^^^^^^
* The ``max_age`` parameter of the
:meth:`django.core.signing.TimestampSigner.unsign` method now also accept a
:py:class:`datetime.timedelta` object.
Database backends
^^^^^^^^^^^^^^^^^
* The MySQL backend no longer strips microseconds from ``datetime`` values as
MySQL 5.6.4 and up supports fractional seconds depending on the declaration
of the datetime field (when ``DATETIME`` includes fractional precision greater
than 0). New datetime database columns created with Django 1.8 and MySQL 5.6.4
and up will support microseconds. See the :ref:`MySQL database notes
<mysql-fractional-seconds>` for more details.
* The MySQL backend no longer creates explicit indexes for foreign keys when
using the InnoDB storage engine, as MySQL already creates them automatically.
Email
^^^^^
* :ref:`Email backends <topic-email-backends>` now support the context manager
protocol for opening and closing connections.
* The SMTP email backend now supports ``keyfile`` and ``certfile``
authentication with the :setting:`EMAIL_SSL_CERTFILE` and
:setting:`EMAIL_SSL_KEYFILE` settings.
* The SMTP :class:`~django.core.mail.backends.smtp.EmailBackend` now supports
setting the ``timeout`` parameter with the :setting:`EMAIL_TIMEOUT` setting.
* :class:`~django.core.mail.EmailMessage` and ``EmailMultiAlternatives`` now
support the ``reply_to`` parameter.
File Storage
^^^^^^^^^^^^
* :meth:`Storage.get_available_name()
<django.core.files.storage.Storage.get_available_name>` and
:meth:`Storage.save() <django.core.files.storage.Storage.save>`
now take a ``max_length`` argument to implement storage-level maximum
filename length constraints. Filenames exceeding this argument will get
truncated. This prevents a database error when appending a unique suffix to a
long filename that already exists on the storage. See the :ref:`deprecation
note <storage-max-length-update>` about adding this argument to your custom
storage classes.
File Uploads
^^^^^^^^^^^^
* ...
Forms
^^^^^
* Form widgets now render attributes with a value of ``True`` or ``False``
as HTML5 boolean attributes.
* The new :meth:`~django.forms.Form.has_error()` method allows checking
if a specific error has happened.
* If :attr:`~django.forms.Form.required_css_class` is defined on a form, then
the ``<label>`` tags for required fields will have this class present in its
attributes.
* The rendering of non-field errors in unordered lists (``<ul>``) now includes
``nonfield`` in its list of classes to distinguish them from field-specific
errors.
* :class:`~django.forms.Field` now accepts a
:attr:`~django.forms.Field.label_suffix` argument, which will override the
form's :attr:`~django.forms.Form.label_suffix`. This enables customizing the
suffix on a per-field basis — previously it wasn't possible to override
a form's :attr:`~django.forms.Form.label_suffix` while using shortcuts such
as ``{{ form.as_p }}`` in templates.
* :class:`~django.forms.extras.widgets.SelectDateWidget` now accepts an
:attr:`~django.forms.extras.widgets.SelectDateWidget.empty_label` argument, which will
override the top list choice label when :class:`~django.forms.DateField` is not required.
* After an :class:`~django.forms.ImageField` has been cleaned and validated, the
``UploadedFile`` object will have an additional ``image`` attribute containing
the Pillow ``Image`` instance used to check if the file was a valid image. It
will also update ``UploadedFile.content_type`` with the image's content type
as determined by Pillow.
* You can now pass a callable that returns an iterable of choices when
instantiating a :class:`~django.forms.ChoiceField`.
Generic Views
^^^^^^^^^^^^^
* Generic views that use :class:`~django.views.generic.list.MultipleObjectMixin`
may now specify the ordering applied to the
:attr:`~django.views.generic.list.MultipleObjectMixin.queryset` by setting
:attr:`~django.views.generic.list.MultipleObjectMixin.ordering` or overriding
:meth:`~django.views.generic.list.MultipleObjectMixin.get_ordering()`.
* The new :attr:`SingleObjectMixin.query_pk_and_slug
<django.views.generic.detail.SingleObjectMixin.query_pk_and_slug>`
attribute allows changing the behavior of
:meth:`~django.views.generic.detail.SingleObjectMixin.get_object()`
so that it'll perform its lookup using both the primary key and the slug.
* The :meth:`~django.views.generic.edit.FormMixin.get_form()` method doesn't
require a ``form_class`` to be provided anymore. If not provided ``form_class``
defaults to :meth:`~django.views.generic.edit.FormMixin.get_form_class()`.
* Placeholders in :attr:`ModelFormMixin.success_url
<django.views.generic.edit.ModelFormMixin.success_url>` now support the Python
:py:meth:`str.format()` syntax. The legacy ``%(<foo>)s`` syntax is still
supported but will be removed in Django 2.0.
Internationalization
^^^^^^^^^^^^^^^^^^^^
* :setting:`FORMAT_MODULE_PATH` can now be a list of strings representing
module paths. This allows importing several format modules from different
reusable apps. It also allows overriding those custom formats in your main
Django project.
Logging
^^^^^^^
* The :class:`django.utils.log.AdminEmailHandler` class now has a
:meth:`~django.utils.log.AdminEmailHandler.send_mail` method to make it more
subclass friendly.
Management Commands
^^^^^^^^^^^^^^^^^^^
* Database connections are now always closed after a management command called
from the command line has finished doing its job.
* Commands from alternate package formats like eggs are now also discovered.
* :djadmin:`dumpdata` now has the option :djadminopt:`--output` which allows
specifying the file to which the serialized data is written.
* :djadmin:`makemessages` and :djadmin:`compilemessages` now have the option
:djadminopt:`--exclude` which allows exclusion of specific locales from
processing.
* :djadmin:`compilemessages` now has a ``--use-fuzzy`` or ``-f`` option which
includes fuzzy translations into compiled files.
* The :djadminopt:`--ignorenonexistent` option of the :djadmin:`loaddata`
management command now ignores data for models that no longer exist.
* :djadmin:`runserver` now uses daemon threads for faster reloading.
* :djadmin:`inspectdb` now outputs ``Meta.unique_together``. It is also able to
introspect :class:`~django.db.models.AutoField` for MySQL and PostgreSQL
databases.
* When calling management commands from code through :ref:`call_command
<call-command>` and passing options, the option name can match the command
line option name (without the initial dashes) or the final option destination
variable name, but in either case, the resulting option received by the
command is now always the ``dest`` name specified in the command option
definition (as long as the command uses the new :py:mod:`argparse` module).
* The :djadmin:`dbshell` command now supports MySQL's optional SSL certificate
authority setting (``--ssl-ca``).
* The :djadminopt:`--name` option for :djadmin:`makemigrations` allows you to
to give the migration(s) a custom name instead of a generated one.
* The :djadmin:`loaddata` command now prevents repeated fixture loading. If
:setting:`FIXTURE_DIRS` contains duplicates or a default fixture directory
path (``app_name/fixtures``), an exception is raised.
* :djadmin:`makemigrations` now supports an :djadminopt:`--exit` option to
exit with an error code if no migrations are created.
* The new :djadmin:`showmigrations` command allows listing all migrations and
their dependencies in a project.
Middleware
^^^^^^^^^^
* The :attr:`CommonMiddleware.response_redirect_class
<django.middleware.common.CommonMiddleware.response_redirect_class>`
attribute allows you to customize the redirects issued by the middleware.
* A debug message will be logged to the ``django.request`` logger when a
middleware raises a :exc:`~django.core.exceptions.MiddlewareNotUsed` exception
in :setting:`DEBUG` mode.
Migrations
^^^^^^^^^^
* The :class:`~django.db.migrations.operations.RunSQL` operation can now handle
parameters passed to the SQL statements.
* It is now possible to have migrations (most probably :ref:`data migrations
<data-migrations>`) for applications without models.
* Migrations can now :ref:`serialize model managers
<using-managers-in-migrations>` as part of the model state.
* A :ref:`generic mechanism to handle the deprecation of model fields
<migrations-removing-model-fields>` was added.
* The :attr:`RunPython.noop <django.db.migrations.operations.RunPython.noop>`
and :meth:`RunSQL.noop() <django.db.migrations.operations.RunSQL.noop>` class
attribute/method were added to ease in making ``RunPython`` and ``RunSQL``
operations reversible.
* The :class:`~django.db.migrations.operations.RunPython` and
:class:`~django.db.migrations.operations.RunSQL` operations now accept a
``hints`` parameter that will be passed to :meth:`allow_migrate`. To take
advantage of this feature you must ensure that the ``allow_migrate()`` method
of all your routers accept ``**hints``.
Models
^^^^^^
* Django now logs at most 9000 queries in ``connections.queries``, in order
to prevent excessive memory usage in long-running processes in debug mode.
* There is now a model ``Meta`` option to define a
:attr:`default related name <django.db.models.Options.default_related_name>`
for all relational fields of a model.
* Pickling models and querysets across different versions of Django isn't
officially supported (it may work, but there's no guarantee). An extra
variable that specifies the current Django version is now added to the
pickled state of models and querysets, and Django raises a ``RuntimeWarning``
when these objects are unpickled in a different version than the one in
which they were pickled.
* Added :meth:`Model.from_db() <django.db.models.Model.from_db()>` which
Django uses whenever objects are loaded using the ORM. The method allows
customizing model loading behavior.
* ``extra(select={...})`` now allows you to escape a literal ``%s`` sequence
using ``%%s``.
* :doc:`Custom Lookups</howto/custom-lookups>` can now be registered using
a decorator pattern.
* The new :attr:`Transform.bilateral <django.db.models.Transform.bilateral>`
attribute allows creating bilateral transformations. These transformations
are applied to both ``lhs`` and ``rhs`` when used in a lookup expression,
providing opportunities for more sophisticated lookups.
* SQL special characters (\, %, _) are now escaped properly when a pattern
lookup (e.g. ``contains``, ``startswith``, etc.) is used with an ``F()``
expression as the right-hand side. In those cases, the escaping is performed
by the database, which can lead to somewhat complex queries involving nested
``REPLACE`` function calls.
* You can now refresh model instances by using :meth:`Model.refresh_from_db()
<django.db.models.Model.refresh_from_db>`.
* You can now get the set of deferred fields for a model using
:meth:`Model.get_deferred_fields() <django.db.models.Model.get_deferred_fields>`.
Signals
^^^^^^^
* Exceptions from the ``(receiver, exception)`` tuples returned by
:meth:`Signal.send_robust() <django.dispatch.Signal.send_robust>` now have
their traceback attached as a ``__traceback__`` attribute.
* The ``environ`` argument, which contains the WSGI environment structure from
the request, was added to the :data:`~django.core.signals.request_started`
signal.
* You can now import the :func:`~django.test.signals.setting_changed` signal
from ``django.core.signals`` to avoid loading ``django.test`` in non-test
situations. Django no longer does so itself.
System Check Framework
^^^^^^^^^^^^^^^^^^^^^^
* :attr:`~django.core.checks.register` can now be used as a function.
Templates
^^^^^^^^^
* :tfilter:`urlize` now supports domain-only links that include characters after
the top-level domain (e.g. ``djangoproject.com/`` and
``djangoproject.com/download/``).
* :tfilter:`urlize` doesn't treat exclamation marks at the end of a domain or
its query string as part of the URL (the URL in e.g. ``'djangoproject.com!``
is ``djangoproject.com``)
* Added a :class:`locmem.Loader <django.template.loaders.locmem.Loader>`
class that loads Django templates from a Python dictionary.
* The :ttag:`now` tag can now store its output in a context variable with the
usual syntax: ``{% now 'j n Y' as varname %}``.
Requests and Responses
^^^^^^^^^^^^^^^^^^^^^^
* ``WSGIRequest`` now respects paths starting with ``//``.
* The :meth:`HttpRequest.build_absolute_uri()
<django.http.HttpRequest.build_absolute_uri>` method now handles paths
starting with ``//`` correctly.
* If :setting:`DEBUG` is ``True`` and a request raises a
:exc:`~django.core.exceptions.SuspiciousOperation`, the response will be
rendered with a detailed error page.
* The ``query_string`` argument of :class:`~django.http.QueryDict` is now
optional, defaulting to ``None``, so a blank ``QueryDict`` can now be
instantiated with ``QueryDict()`` instead of ``QueryDict(None)`` or
``QueryDict('')``.
* The ``GET`` and ``POST`` attributes of an :class:`~django.http.HttpRequest`
object are now :class:`~django.http.QueryDict`\s rather than dictionaries,
and the ``FILES`` attribute is now a ``MultiValueDict``.
This brings this class into line with the documentation and with
``WSGIRequest``.
* The :attr:`HttpResponse.charset <django.http.HttpResponse.charset>` attribute
was added.
* ``WSGIRequestHandler`` now follows RFC in converting URI to IRI, using
``uri_to_iri()``.
* The :meth:`HttpRequest.get_full_path()
<django.http.HttpRequest.get_full_path>` method now escapes unsafe characters
from the path portion of a Uniform Resource Identifier (URI) properly.
* :class:`~django.http.HttpResponse` now implements a few additional methods
like :meth:`~django.http.HttpResponse.getvalue` so that instances can be used
as stream objects.
* The new :meth:`HttpResponse.setdefault()
<django.http.HttpResponse.setdefault>` method allows setting a header unless
it has already been set.
* You can use the new :class:`~django.http.FileResponse` to stream files.
* The :func:`~django.views.decorators.http.condition` decorator for
conditional view processing now supports the ``If-unmodified-since`` header.
Tests
^^^^^
* The :class:`RequestFactory.trace() <django.test.RequestFactory>`
and :class:`Client.trace() <django.test.Client.trace>` methods were
implemented, allowing you to create ``TRACE`` requests in your tests.
* The ``count`` argument was added to
:meth:`~django.test.SimpleTestCase.assertTemplateUsed`. This allows you to
assert that a template was rendered a specific number of times.
* The new :meth:`~django.test.SimpleTestCase.assertJSONNotEqual` assertion
allows you to test that two JSON fragments are not equal.
* Added options to the :djadmin:`test` command to preserve the test database
(:djadminopt:`--keepdb`), to run the test cases in reverse order
(:djadminopt:`--reverse`), and to enable SQL logging for failing tests
(:djadminopt:`--debug-sql`).
* Added the :attr:`~django.test.Response.resolver_match` attribute to test
client responses.
* Added several settings that allow customization of test tablespace parameters
for Oracle: :setting:`DATAFILE`, :setting:`DATAFILE_TMP`,
:setting:`DATAFILE_MAXSIZE` and :setting:`DATAFILE_TMP_MAXSIZE`.
* The :func:`~django.test.override_settings` decorator can now affect the
master router in :setting:`DATABASE_ROUTERS`.
* Added test client support for file uploads with file-like objects.
* A shared cache is now used when testing with a SQLite in-memory database when
using Python 3.4+ and SQLite 3.7.13+. This allows sharing the database
between threads.
Validators
^^^^^^^^^^
* :class:`~django.core.validators.URLValidator` now supports IPv6 addresses,
unicode domains, and URLs containing authentication data.
Backwards incompatible changes in 1.8
=====================================
.. warning::
In addition to the changes outlined in this section, be sure to review the
:ref:`deprecation plan <deprecation-removed-in-1.8>` for any features that
have been removed. If you haven't updated your code within the
deprecation timeline for a given feature, its removal may appear as a
backwards incompatible change.
Related object operations are run in a transaction
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Some operations on related objects such as
:meth:`~django.db.models.fields.related.RelatedManager.add()` or
:ref:`direct assignment<direct-assignment>` ran multiple data modifying
queries without wrapping them in transactions. To reduce the risk of data
corruption, all data modifying methods that affect multiple related objects
(i.e. ``add()``, ``remove()``, ``clear()``, and :ref:`direct assignment
<direct-assignment>`) now perform their data modifying queries from within a
transaction, provided your database supports transactions.
This has one backwards incompatible side effect, signal handlers triggered from
these methods are now executed within the method's transaction and any
exception in a signal handler will prevent the whole operation.
Assigning unsaved objects to relations raises an error
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Assigning unsaved objects to a :class:`~django.db.models.ForeignKey`,
:class:`~django.contrib.contenttypes.fields.GenericForeignKey`, and
:class:`~django.db.models.OneToOneField` now raises a :exc:`ValueError`.
Previously, the assignment of an unsaved object would be silently ignored.
For example::
>>> book = Book.objects.create(name="Django")
>>> book.author = Author(name="John")
>>> book.author.save()
>>> book.save()
>>> Book.objects.get(name="Django")
>>> book.author
>>>
Now, an error will be raised to prevent data loss::
>>> book.author = Author(name="john")
Traceback (most recent call last):
...
ValueError: Cannot assign "<Author: John>": "Author" instance isn't saved in the database.
Management commands that only accept positional arguments
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
If you have written a custom management command that only accepts positional
arguments and you didn't specify the
:attr:`~django.core.management.BaseCommand.args` command variable, you might
get an error like ``Error: unrecognized arguments: ...``, as variable parsing
is now based on :py:mod:`argparse` which doesn't implicitly accept positional
arguments. You can make your command backwards compatible by simply setting the
:attr:`~django.core.management.BaseCommand.args` class variable. However, if
you don't have to keep compatibility with older Django versions, it's better to
implement the new :meth:`~django.core.management.BaseCommand.add_arguments`
method as described in :doc:`/howto/custom-management-commands`.
Custom test management command arguments through test runner
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The method to add custom arguments to the `test` management command through the
test runner has changed. Previously, you could provide an `option_list` class
variable on the test runner to add more arguments (à la :py:mod:`optparse`).
Now to implement the same behavior, you have to create an
``add_arguments(cls, parser)`` class method on the test runner and call
``parser.add_argument`` to add any custom arguments, as parser is now an
:py:class:`argparse.ArgumentParser` instance.
Model check ensures auto-generated column names are within limits specified by database
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
A field name that's longer than the column name length supported by a database
can create problems. For example, with MySQL you'll get an exception trying to
create the column, and with PostgreSQL the column name is truncated by the
database (you may see a warning in the PostgreSQL logs).
A model check has been introduced to better alert users to this scenario before
the actual creation of database tables.
If you have an existing model where this check seems to be a false positive,
for example on PostgreSQL where the name was already being truncated, simply
use :attr:`~django.db.models.Field.db_column` to specify the name that's being
used.
The check also applies to the columns generated in an implicit
``ManyToManyField.through`` model. If you run into an issue there, use
:attr:`~django.db.models.ManyToManyField.through` to create an explicit model
and then specify :attr:`~django.db.models.Field.db_column` on its column(s)
as needed.
Query relation lookups now check object types
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Querying for model lookups now checks if the object passed is of correct type
and raises a :exc:`ValueError` if not. Previously, Django didn't care if the
object was of correct type; it just used the object's related field attribute
(e.g. ``id``) for the lookup. Now, an error is raised to prevent incorrect
lookups::
>>> book = Book.objects.create(name="Django")
>>> book = Book.objects.filter(author=book)
Traceback (most recent call last):
...
ValueError: Cannot query "<Book: Django>": Must be "Author" instance.
``select_related()`` now checks given fields
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
``select_related()`` now validates that the given fields actually exist.
Previously, nonexistent fields were silently ignored. Now, an error is raised::
>>> book = Book.objects.select_related('nonexistent_field')
Traceback (most recent call last):
...
FieldError: Invalid field name(s) given in select_related: 'nonexistent_field'
The validation also makes sure that the given field is relational::
>>> book = Book.objects.select_related('name')
Traceback (most recent call last):
...
FieldError: Non-relational field given in select_related: 'name'
Default ``EmailField.max_length`` increased to 254
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The old default 75 character ``max_length`` was not capable of storing all
possible RFC3696/5321-compliant email addresses. In order to store all
possible valid email addresses, the ``max_length`` has been increased to 254
characters. You will need to generate and apply database migrations for your
affected models (or add ``max_length=75`` if you wish to keep the length on
your current fields). A migration for
:attr:`django.contrib.auth.models.User.email` is included.
Support for PostgreSQL versions older than 9.0
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The end of upstream support periods was reached in July 2014 for PostgreSQL 8.4.
As a consequence, Django 1.8 sets 9.0 as the minimum PostgreSQL version it
officially supports.
This also includes dropping support for PostGIS 1.3 and 1.4 as these versions
are not supported on versions of PostgreSQL later than 8.4.
Django also now requires the use of Psycopg2 version 2.0.9 or higher.
Support for MySQL versions older than 5.5
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The end of upstream support periods was reached in January 2012 for MySQL 5.0
and December 2013 for MySQL 5.1. As a consequence, Django 1.8 sets 5.5 as the
minimum MySQL version it officially supports.
Support for Oracle versions older than 11.1
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The end of upstream support periods was reached in July 2010 for Oracle 9.2,
January 2012 for Oracle 10.1, and July 2013 for Oracle 10.2. As a consequence,
Django 1.8 sets 11.1 as the minimum Oracle version it officially supports.
Specific privileges used instead of roles for tests on Oracle
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Earlier versions of Django granted the CONNECT and RESOURCE roles to the test
user on Oracle. These roles have been deprecated, so Django 1.8 uses the
specific underlying privileges instead. This changes the privileges required
of the main user for running tests (unless the project is configured to avoid
creating a test user). The exact privileges required now are detailed in
:ref:`Oracle notes <oracle-notes>`.
``AbstractUser.last_login`` allows null values
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The :attr:`AbstractUser.last_login <django.contrib.auth.models.User.last_login>`
field now allows null values. Previously, it defaulted to the time when the user
was created which was misleading if the user never logged in. Please run the
database migration. If your custom user inherits from ``AbstractUser`` and you
wish to set ``last_login`` to ``NULL`` for users who haven't logged in, you can
run this query::
from django.db import models
from django.contrib.auth import get_user_model
from django.contrib.auth.models import AbstractBaseUser
UserModel = get_user_model()
if issubclass(UserModel, AbstractBaseUser):
UserModel._default_manager.filter(
last_login=models.F('date_joined')
).update(last_login=None)
:mod:`django.contrib.gis`
~~~~~~~~~~~~~~~~~~~~~~~~~
* Support for GEOS 3.1 and GDAL 1.6 has been dropped.
* Support for SpatiaLite < 2.4 has been dropped.
* GIS-specific lookups have been refactored to use the
:class:`django.db.models.Lookup` API.
* The default ``str`` representation of
:class:`~django.contrib.gis.geos.GEOSGeometry` objects has been changed from
WKT to EWKT format (including the SRID). As this representation is used in
the serialization framework, that means that ``dumpdata`` output will now
contain the SRID value of geometry objects.
Priority of context processors for ``TemplateResponse`` brought in line with ``render``
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The :class:`~django.template.response.TemplateResponse` constructor is designed to be a
drop-in replacement for the :func:`~django.shortcuts.render` function. However,
it had a slight incompatibility, in that for ``TemplateResponse``, context data
from the passed in context dictionary could be shadowed by context data returned
from context processors, whereas for ``render`` it was the other way
around. This was a bug, and the behavior of ``render`` is more appropriate,
since it allows the globally defined context processors to be overridden locally
in the view. If you were relying on the fact context data in a
``TemplateResponse`` could be overridden using a context processor, you will
need to change your code.
Overriding ``setUpClass`` / ``tearDownClass`` in test cases
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The decorators :func:`~django.test.override_settings` and
:func:`~django.test.modify_settings` now act at the class level when used as
class decorators. As a consequence, when overriding ``setUpClass()`` or
``tearDownClass()``, the ``super`` implementation should always be called.
Removal of ``django.contrib.formtools``
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The formtools contrib app has been moved into a separate package.
``django.contrib.formtools`` itself has been removed. The docs provide
:ref:`migration instructions <formtools-how-to-migrate>`.
The new package is available `on Github`_ and on PyPI.
.. _on GitHub: https://github.com/django/django-formtools/
Database connection reloading between tests
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Django previously closed database connections between each test within a
``TestCase``. This is no longer the case as Django now wraps the whole
``TestCase`` within a transaction. If some of your tests relied on the old
behavior, you should have them inherit from ``TransactionTestCase`` instead.
Cleanup of the ``django.template`` namespace
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
If you've been relying on private APIs exposed in the ``django.template``
module, you may have to import them from ``django.template.base`` instead.
Also private APIs ``django.template.base.compile_string()``,
``django.template.loader.find_template()``, and
``django.template.loader.get_template_from_string()`` were removed.
Database backend API
~~~~~~~~~~~~~~~~~~~~
The following changes to the database backend API are documented to assist
those writing third-party backends in updating their code:
* ``BaseDatabaseXXX`` classes have been moved to ``django.db.backends.base``.
Please import them from the new locations::
from django.db.backends.base.base import BaseDatabaseWrapper
from django.db.backends.base.client import BaseDatabaseClient
from django.db.backends.base.creation import BaseDatabaseCreation
from django.db.backends.base.features import BaseDatabaseFeatures
from django.db.backends.base.introspection import BaseDatabaseIntrospection
from django.db.backends.base.introspection import FieldInfo, TableInfo
from django.db.backends.base.operations import BaseDatabaseOperations
from django.db.backends.base.schema import BaseDatabaseSchemaEditor
from django.db.backends.base.validation import BaseDatabaseValidation
* The ``data_types``, ``data_types_suffix``, and
``data_type_check_constraints`` attributes have moved from the
``DatabaseCreation`` class to ``DatabaseWrapper``.
:mod:`django.contrib.admin`
~~~~~~~~~~~~~~~~~~~~~~~~~~~
* ``AdminSite`` no longer takes an ``app_name`` argument and its ``app_name``
attribute has been removed. The application name is always ``admin`` (as
opposed to the instance name which you can still customize using
``AdminSite(name="...")``.
* The ``ModelAdmin.get_object()`` method (private API) now takes a third
argument named ``from_field`` in order to specify which field should match
the provided ``object_id``.
* The :meth:`ModelAdmin.response_delete()
<django.contrib.admin.ModelAdmin.response_delete>` method
now takes a second argument named ``obj_id`` which is the serialized
identifier used to retrieve the object before deletion.
Miscellaneous
~~~~~~~~~~~~~
* ``connections.queries`` is now a read-only attribute.
* Database connections are considered equal only if they're the same object.
They aren't hashable any more.
* :class:`~django.middleware.gzip.GZipMiddleware` used to disable compression
for some content types when the request is from Internet Explorer, in order
to work around a bug in IE6 and earlier. This behavior could affect
performance on IE7 and later. It was removed.
* ``URLField.to_python`` no longer adds a trailing slash to pathless URLs.
* The :tfilter:`length` template filter now returns ``0`` for an undefined
variable, rather than an empty string.
* ``ForeignKey.default_error_message['invalid']`` has been changed from
``'%(model)s instance with pk %(pk)r does not exist.'`` to
``'%(model)s instance with %(field)s %(value)r does not exist.'`` If you are
using this message in your own code, please update the list of interpolated