forked from django/django
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path1.4.txt
1337 lines (1010 loc) · 56.4 KB
/
1.4.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.4 release notes
========================
*March 23, 2012*
Welcome to Django 1.4!
These release notes cover the :ref:`new features <whats-new-1.4>`, as well as
some :ref:`backwards incompatible changes <backwards-incompatible-1.4>` you'll
want to be aware of when upgrading from Django 1.3 or older versions. We've
also dropped some features, which are detailed in :ref:`our deprecation plan
<deprecation-removed-in-1.4>`, and we've :ref:`begun the deprecation process
for some features <deprecated-features-1.4>`.
Overview
========
The biggest new feature in Django 1.4 is `support for time zones`_ when
handling date/times. When enabled, this Django will store date/times in UTC,
use timezone-aware objects internally, and translate them to users' local
timezones for display.
If you're upgrading an existing project to Django 1.4, switching to the timezone
aware mode may take some care: the new mode disallows some rather sloppy
behavior that used to be accepted. We encourage anyone who's upgrading to check
out the :ref:`timezone migration guide <time-zones-migration-guide>` and the
:ref:`timezone FAQ <time-zones-faq>` for useful pointers.
Other notable new features in Django 1.4 include:
* A number of ORM improvements, including `SELECT FOR UPDATE support`_,
the ability to `bulk insert <#model-objects-bulk-create-in-the-orm>`_
large datasets for improved performance, and
`QuerySet.prefetch_related`_, a method to batch-load related objects
in areas where :meth:`~django.db.models.query.QuerySet.select_related`
doesn't work.
* Some nice security additions, including `improved password hashing`_
(featuring PBKDF2_ and bcrypt_ support), new `tools for cryptographic
signing`_, several `CSRF improvements`_, and `simple clickjacking
protection`_.
* An `updated default project layout and manage.py`_ that removes the "magic"
from prior versions. And for those who don't like the new layout, you can
use `custom project and app templates`_ instead!
* `Support for in-browser testing frameworks`_ (like Selenium_).
* ... and a whole lot more; `see below <#what-s-new-in-django-1-4>`_!
Wherever possible we try to introduce new features in a backwards-compatible
manner per :doc:`our API stability policy </misc/api-stability>` policy.
However, as with previous releases, Django 1.4 ships with some minor
:ref:`backwards incompatible changes <backwards-incompatible-1.4>`; people
upgrading from previous versions of Django should read that list carefully.
Python compatibility
====================
Django 1.4 has dropped support for Python 2.4. Python 2.5 is now the minimum
required Python version. Django is tested and supported on Python 2.5, 2.6 and
2.7.
This change should affect only a small number of Django users, as most
operating-system vendors today are shipping Python 2.5 or newer as their default
version. If you're still using Python 2.4, however, you'll need to stick to
Django 1.3 until you can upgrade. Per :doc:`our support policy
</internals/release-process>`, Django 1.3 will continue to receive security
support until the release of Django 1.5.
Django does not support Python 3.x at this time. At some point before the
release of Django 1.4, we plan to publish a document outlining our full
timeline for deprecating Python 2.x and moving to Python 3.x.
.. _whats-new-1.4:
What's new in Django 1.4
========================
Support for time zones
----------------------
In previous versions, Django used "naive" date/times (that is, date/times
without an associated time zone), leaving it up to each developer to interpret
what a given date/time "really means". This can cause all sorts of subtle
timezone-related bugs.
In Django 1.4, you can now switch Django into a more correct, time-zone aware
mode. In this mode, Django stores date and time information in UTC in the
database, uses time-zone-aware datetime objects internally and translates them
to the end user's time zone in templates and forms. Reasons for using this
feature include:
- Customizing date and time display for users around the world.
- Storing datetimes in UTC for database portability and interoperability.
(This argument doesn't apply to PostgreSQL, because it already stores
timestamps with time zone information in Django 1.3.)
- Avoiding data corruption problems around DST transitions.
Time zone support is enabled by default in new projects created with
:djadmin:`startproject`. If you want to use this feature in an existing
project, read the :ref:`migration guide <time-zones-migration-guide>`. If you
encounter problems, there's a helpful :ref:`FAQ <time-zones-faq>`.
Support for in-browser testing frameworks
-----------------------------------------
Django 1.4 supports integration with in-browser testing frameworks like
Selenium_. The new :class:`django.test.LiveServerTestCase` base class lets you
test the interactions between your site's front and back ends more
comprehensively. See the
:class:`documentation<django.test.LiveServerTestCase>` for more details and
concrete examples.
.. _Selenium: http://seleniumhq.org/
Updated default project layout and ``manage.py``
------------------------------------------------
Django 1.4 ships with an updated default project layout and ``manage.py`` file
for the :djadmin:`startproject` management command. These fix some issues with
the previous ``manage.py`` handling of Python import paths that caused double
imports, trouble moving from development to deployment, and other
difficult-to-debug path issues.
The previous ``manage.py`` called functions that are now deprecated, and thus
projects upgrading to Django 1.4 should update their ``manage.py``. (The
old-style ``manage.py`` will continue to work as before until Django 1.6. In
1.5 it will raise ``DeprecationWarning``).
The new recommended ``manage.py`` file should look like this::
#!/usr/bin/env python
import os, sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "{{ project_name }}.settings")
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv)
``{{ project_name }}`` should be replaced with the Python package name of the
actual project.
If settings, URLconfs and apps within the project are imported or referenced
using the project name prefix (e.g. ``myproject.settings``, ``ROOT_URLCONF =
"myproject.urls"``, etc.), the new ``manage.py`` will need to be moved one
directory up, so it is outside the project package rather than adjacent to
``settings.py`` and ``urls.py``.
For instance, with the following layout::
manage.py
mysite/
__init__.py
settings.py
urls.py
myapp/
__init__.py
models.py
You could import ``mysite.settings``, ``mysite.urls``, and ``mysite.myapp``,
but not ``settings``, ``urls``, or ``myapp`` as top-level modules.
Anything imported as a top-level module can be placed adjacent to the new
``manage.py``. For instance, to decouple "myapp" from the project module and
import it as just ``myapp``, place it outside the ``mysite/`` directory::
manage.py
myapp/
__init__.py
models.py
mysite/
__init__.py
settings.py
urls.py
If the same code is imported inconsistently (some places with the project
prefix, some places without it), the imports will need to be cleaned up when
switching to the new ``manage.py``.
Custom project and app templates
--------------------------------
The :djadmin:`startapp` and :djadmin:`startproject` management commands
now have a ``--template`` option for specifying a path or URL to a custom app
or project template.
For example, Django will use the ``/path/to/my_project_template`` directory
when you run the following command::
django-admin.py startproject --template=/path/to/my_project_template myproject
You can also now provide a destination directory as the second
argument to both :djadmin:`startapp` and :djadmin:`startproject`::
django-admin.py startapp myapp /path/to/new/app
django-admin.py startproject myproject /path/to/new/project
For more information, see the :djadmin:`startapp` and :djadmin:`startproject`
documentation.
Improved WSGI support
---------------------
The :djadmin:`startproject` management command now adds a :file:`wsgi.py`
module to the initial project layout, containing a simple WSGI application that
can be used for :doc:`deploying with WSGI app
servers</howto/deployment/wsgi/index>`.
The :djadmin:`built-in development server<runserver>` now supports using an
externally-defined WSGI callable, which makes it possible to run runserver
with the same WSGI configuration that is used for deployment. The new
:setting:`WSGI_APPLICATION` setting lets you configure which WSGI callable
:djadmin:`runserver` uses.
(The ``runfcgi`` management command also internally wraps the WSGI
callable configured via :setting:`WSGI_APPLICATION`.)
``SELECT FOR UPDATE`` support
-----------------------------
Django 1.4 includes a :meth:`QuerySet.select_for_update()
<django.db.models.query.QuerySet.select_for_update>` method, which generates a
``SELECT ... FOR UPDATE`` SQL query. This will lock rows until the end of the
transaction, meaning other transactions cannot modify or delete rows matched by
a ``FOR UPDATE`` query.
For more details, see the documentation for
:meth:`~django.db.models.query.QuerySet.select_for_update`.
``Model.objects.bulk_create`` in the ORM
----------------------------------------
This method lets you create multiple objects more efficiently. It can result in
significant performance increases if you have many objects.
Django makes use of this internally, meaning some operations (such as database
setup for test suites) have seen a performance benefit as a result.
See the :meth:`~django.db.models.query.QuerySet.bulk_create` docs for more
information.
``QuerySet.prefetch_related``
-----------------------------
Similar to :meth:`~django.db.models.query.QuerySet.select_related` but with a
different strategy and broader scope,
:meth:`~django.db.models.query.QuerySet.prefetch_related` has been added to
:class:`~django.db.models.query.QuerySet`. This method returns a new
``QuerySet`` that will prefetch each of the specified related lookups in a
single batch as soon as the query begins to be evaluated. Unlike
``select_related``, it does the joins in Python, not in the database, and
supports many-to-many relationships, ``GenericForeignKey`` and more. This
allows you to fix a very common performance problem in which your code ends up
doing O(n) database queries (or worse) if objects on your primary ``QuerySet``
each have many related objects that you also need to fetch.
Improved password hashing
-------------------------
Django's auth system (``django.contrib.auth``) stores passwords using a one-way
algorithm. Django 1.3 uses the SHA1_ algorithm, but increasing processor speeds
and theoretical attacks have revealed that SHA1 isn't as secure as we'd like.
Thus, Django 1.4 introduces a new password storage system: by default Django now
uses the PBKDF2_ algorithm (as recommended by NIST_). You can also easily choose
a different algorithm (including the popular bcrypt_ algorithm). For more
details, see :ref:`auth_password_storage`.
.. _sha1: https://en.wikipedia.org/wiki/SHA1
.. _pbkdf2: https://en.wikipedia.org/wiki/PBKDF2
.. _nist: http://csrc.nist.gov/publications/nistpubs/800-132/nist-sp800-132.pdf
.. _bcrypt: https://en.wikipedia.org/wiki/Bcrypt
HTML5 doctype
-------------
We've switched the admin and other bundled templates to use the HTML5
doctype. While Django will be careful to maintain compatibility with older
browsers, this change means that you can use any HTML5 features you need in
admin pages without having to lose HTML validity or override the provided
templates to change the doctype.
List filters in admin interface
-------------------------------
Prior to Django 1.4, the :mod:`~django.contrib.admin` app let you specify
change list filters by specifying a field lookup, but it didn't allow you to
create custom filters. This has been rectified with a simple API (previously
used internally and known as "FilterSpec"). For more details, see the
documentation for :attr:`~django.contrib.admin.ModelAdmin.list_filter`.
Multiple sort in admin interface
--------------------------------
The admin change list now supports sorting on multiple columns. It respects all
elements of the :attr:`~django.contrib.admin.ModelAdmin.ordering` attribute, and
sorting on multiple columns by clicking on headers is designed to mimic the
behavior of desktop GUIs. We also added a
:meth:`~django.contrib.admin.ModelAdmin.get_ordering` method for specifying the
ordering dynamically (i.e., depending on the request).
New ``ModelAdmin`` methods
--------------------------
We added a :meth:`~django.contrib.admin.ModelAdmin.save_related` method to
:mod:`~django.contrib.admin.ModelAdmin` to ease customization of how
related objects are saved in the admin.
Two other new :class:`~django.contrib.admin.ModelAdmin` methods,
:meth:`~django.contrib.admin.ModelAdmin.get_list_display` and
:meth:`~django.contrib.admin.ModelAdmin.get_list_display_links`
enable dynamic customization of fields and links displayed on the admin
change list.
Admin inlines respect user permissions
--------------------------------------
Admin inlines now only allow those actions for which the user has
permission. For ``ManyToMany`` relationships with an auto-created intermediate
model (which does not have its own permissions), the change permission for the
related model determines if the user has the permission to add, change or
delete relationships.
Tools for cryptographic signing
-------------------------------
Django 1.4 adds both a low-level API for signing values and a high-level API
for setting and reading signed cookies, one of the most common uses of
signing in Web applications.
See the :doc:`cryptographic signing </topics/signing>` docs for more
information.
Cookie-based session backend
----------------------------
Django 1.4 introduces a cookie-based session backend that uses the tools for
:doc:`cryptographic signing </topics/signing>` to store the session data in
the client's browser.
.. warning::
Session data is signed and validated by the server, but it's not
encrypted. This means a user can view any data stored in the
session but cannot change it. Please read the documentation for
further clarification before using this backend.
See the :ref:`cookie-based session backend <cookie-session-backend>` docs for
more information.
New form wizard
---------------
The previous ``FormWizard`` from ``django.contrib.formtools`` has been
replaced with a new implementation based on the class-based views
introduced in Django 1.3. It features a pluggable storage API and doesn't
require the wizard to pass around hidden fields for every previous step.
Django 1.4 ships with a session-based storage backend and a cookie-based
storage backend. The latter uses the tools for
:doc:`cryptographic signing </topics/signing>` also introduced in
Django 1.4 to store the wizard's state in the user's cookies.
``reverse_lazy``
----------------
A lazily evaluated version of ``reverse()`` was added to allow using URL
reversals before the project's URLconf gets loaded.
Translating URL patterns
------------------------
Django can now look for a language prefix in the URLpattern when using the new
:func:`~django.conf.urls.i18n.i18n_patterns` helper function.
It's also now possible to define translatable URL patterns using
:func:`~django.utils.translation.ugettext_lazy`. See
:ref:`url-internationalization` for more information about the language prefix
and how to internationalize URL patterns.
Contextual translation support for ``{% trans %}`` and ``{% blocktrans %}``
---------------------------------------------------------------------------
The :ref:`contextual translation<contextual-markers>` support introduced in
Django 1.3 via the ``pgettext`` function has been extended to the
:ttag:`trans` and :ttag:`blocktrans` template tags using the new ``context``
keyword.
Customizable ``SingleObjectMixin`` URLConf kwargs
-------------------------------------------------
Two new attributes,
:attr:`pk_url_kwarg<django.views.generic.detail.SingleObjectMixin.pk_url_kwarg>`
and
:attr:`slug_url_kwarg<django.views.generic.detail.SingleObjectMixin.slug_url_kwarg>`,
have been added to :class:`~django.views.generic.detail.SingleObjectMixin` to
enable the customization of URLconf keyword arguments used for single
object generic views.
Assignment template tags
------------------------
A new ``assignment_tag`` helper function was added to ``template.Library`` to
ease the creation of template tags that store data in a specified context
variable.
``*args`` and ``**kwargs`` support for template tag helper functions
--------------------------------------------------------------------
The :ref:`simple_tag<howto-custom-template-tags-simple-tags>`,
:ref:`inclusion_tag <howto-custom-template-tags-inclusion-tags>` and newly
introduced ``assignment_tag`` template helper functions may now accept any
number of positional or keyword arguments. For example::
@register.simple_tag
def my_tag(a, b, *args, **kwargs):
warning = kwargs['warning']
profile = kwargs['profile']
...
return ...
Then, in the template, any number of arguments may be passed to the template tag.
For example:
.. code-block:: html+django
{% my_tag 123 "abcd" book.title warning=message|lower profile=user.profile %}
No wrapping of exceptions in ``TEMPLATE_DEBUG`` mode
----------------------------------------------------
In previous versions of Django, whenever the ``TEMPLATE_DEBUG`` setting
was ``True``, any exception raised during template rendering (even exceptions
unrelated to template syntax) were wrapped in ``TemplateSyntaxError`` and
re-raised. This was done in order to provide detailed template source location
information in the debug 500 page.
In Django 1.4, exceptions are no longer wrapped. Instead, the original
exception is annotated with the source information. This means that catching
exceptions from template rendering is now consistent regardless of the value of
``TEMPLATE_DEBUG``, and there's no need to catch and unwrap
``TemplateSyntaxError`` in order to catch other errors.
``truncatechars`` template filter
---------------------------------
This new filter truncates a string to be no longer than the specified
number of characters. Truncated strings end with a translatable ellipsis
sequence ("..."). See the documentation for :tfilter:`truncatechars` for
more details.
``static`` template tag
-----------------------
The :mod:`staticfiles<django.contrib.staticfiles>` contrib app has a new
``static`` template tag to refer to files saved with the
:setting:`STATICFILES_STORAGE` storage backend. It uses the storage backend's
``url`` method and therefore supports advanced features such as :ref:`serving
files from a cloud service<staticfiles-from-cdn>`.
``CachedStaticFilesStorage`` storage backend
--------------------------------------------
The :mod:`staticfiles<django.contrib.staticfiles>` contrib app now has a
:class:`~django.contrib.staticfiles.storage.CachedStaticFilesStorage` backend
that caches the files it saves (when running the :djadmin:`collectstatic`
management command) by appending the MD5 hash of the file's content to the
filename. For example, the file ``css/styles.css`` would also be saved as
``css/styles.55e7cbb9ba48.css``
See the :class:`~django.contrib.staticfiles.storage.CachedStaticFilesStorage`
docs for more information.
Simple clickjacking protection
------------------------------
We've added a middleware to provide easy protection against `clickjacking
<https://en.wikipedia.org/wiki/Clickjacking>`_ using the ``X-Frame-Options``
header. It's not enabled by default for backwards compatibility reasons, but
you'll almost certainly want to :doc:`enable it </ref/clickjacking/>` to help
plug that security hole for browsers that support the header.
CSRF improvements
-----------------
We've made various improvements to our CSRF features, including the
:func:`~django.views.decorators.csrf.ensure_csrf_cookie` decorator, which can
help with AJAX-heavy sites; protection for PUT and DELETE requests; and the
:setting:`CSRF_COOKIE_SECURE` and :setting:`CSRF_COOKIE_PATH` settings, which can
improve the security and usefulness of CSRF protection. See the :doc:`CSRF
docs </ref/csrf>` for more information.
Error report filtering
----------------------
We added two function decorators,
:func:`~django.views.decorators.debug.sensitive_variables` and
:func:`~django.views.decorators.debug.sensitive_post_parameters`, to allow
designating the local variables and POST parameters that may contain sensitive
information and should be filtered out of error reports.
All POST parameters are now systematically filtered out of error reports for
certain views (``login``, ``password_reset_confirm``, ``password_change`` and
``add_view`` in :mod:`django.contrib.auth.views`, as well as
``user_change_password`` in the admin app) to prevent the leaking of sensitive
information such as user passwords.
You can override or customize the default filtering by writing a :ref:`custom
filter<custom-error-reports>`. For more information see the docs on
:ref:`Filtering error reports<filtering-error-reports>`.
Extended IPv6 support
---------------------
Django 1.4 can now better handle IPv6 addresses with the new
:class:`~django.db.models.GenericIPAddressField` model field,
:class:`~django.forms.GenericIPAddressField` form field and
the validators :data:`~django.core.validators.validate_ipv46_address` and
:data:`~django.core.validators.validate_ipv6_address`.
HTML comparisons in tests
-------------------------
The base classes in :mod:`django.test` now have some helpers to
compare HTML without tripping over irrelevant differences in whitespace,
argument quoting/ordering and closing of self-closing tags. You can either
compare HTML directly with the new
:meth:`~django.test.SimpleTestCase.assertHTMLEqual` and
:meth:`~django.test.SimpleTestCase.assertHTMLNotEqual` assertions, or use
the ``html=True`` flag with
:meth:`~django.test.SimpleTestCase.assertContains` and
:meth:`~django.test.SimpleTestCase.assertNotContains` to test whether the
client's response contains a given HTML fragment. See the :ref:`assertions
documentation <assertions>` for more.
Two new date format strings
---------------------------
Two new :tfilter:`date` formats were added for use in template filters,
template tags and :doc:`/topics/i18n/formatting`:
- ``e`` -- the name of the timezone of the given datetime object
- ``o`` -- the ISO 8601 year number
Please make sure to update your :ref:`custom format files
<custom-format-files>` if they contain either ``e`` or ``o`` in a format
string. For example a Spanish localization format previously only escaped the
``d`` format character::
DATE_FORMAT = r'j \de F \de Y'
But now it needs to also escape ``e`` and ``o``::
DATE_FORMAT = r'j \d\e F \d\e Y'
For more information, see the :tfilter:`date` documentation.
Minor features
--------------
Django 1.4 also includes several smaller improvements worth noting:
* A more usable stacktrace in the technical 500 page. Frames in the
stack trace that reference Django's framework code are dimmed out,
while frames in application code are slightly emphasized. This change
makes it easier to scan a stacktrace for issues in application code.
* :doc:`Tablespace support </topics/db/tablespaces>` in PostgreSQL.
* Customizable names for :meth:`~django.template.Library.simple_tag`.
* In the documentation, a helpful :doc:`security overview </topics/security>`
page.
* The ``django.contrib.auth.models.check_password`` function has been moved
to the :mod:`django.contrib.auth.hashers` module. Importing it from the old
location will still work, but you should update your imports.
* The :djadmin:`collectstatic` management command now has a ``--clear`` option
to delete all files at the destination before copying or linking the static
files.
* It's now possible to load fixtures containing forward references when using
MySQL with the InnoDB database engine.
* A new 403 response handler has been added as
``'django.views.defaults.permission_denied'``. You can set your own handler by
setting the value of :data:`django.conf.urls.handler403`. See the
documentation about :ref:`the 403 (HTTP Forbidden) view<http_forbidden_view>`
for more information.
* The :djadmin:`makemessages` command uses a new and more accurate lexer,
`JsLex`_, for extracting translatable strings from JavaScript files.
.. _JsLex: https://bitbucket.org/ned/jslex
* The :ttag:`trans` template tag now takes an optional ``as`` argument to
be able to retrieve a translation string without displaying it but setting
a template context variable instead.
* The :ttag:`if` template tag now supports ``{% elif %}`` clauses.
* If your Django app is behind a proxy, you might find the new
:setting:`SECURE_PROXY_SSL_HEADER` setting useful. It solves the problem of your
proxy "eating" the fact that a request came in via HTTPS. But only use this
setting if you know what you're doing.
* A new, plain-text, version of the HTTP 500 status code internal error page
served when :setting:`DEBUG` is ``True`` is now sent to the client when
Django detects that the request has originated in JavaScript code.
(:meth:`~django.http.HttpRequest.is_ajax` is used for this.)
Like its HTML counterpart, it contains a collection of different
pieces of information about the state of the application.
This should make it easier to read when debugging interaction with
client-side JavaScript.
* Added the :option:`makemessages --no-location` option.
* Changed the ``locmem`` cache backend to use
``pickle.HIGHEST_PROTOCOL`` for better compatibility with the other
cache backends.
* Added support in the ORM for generating ``SELECT`` queries containing
``DISTINCT ON``.
The ``distinct()`` ``QuerySet`` method now accepts an optional list of model
field names. If specified, then the ``DISTINCT`` statement is limited to these
fields. This is only supported in PostgreSQL.
For more details, see the documentation for
:meth:`~django.db.models.query.QuerySet.distinct`.
* The admin login page will add a password reset link if you include a URL with
the name `'admin_password_reset'` in your urls.py, so plugging in the built-in
password reset mechanism and making it available is now much easier. For
details, see :ref:`auth_password_reset`.
* The MySQL database backend can now make use of the savepoint feature
implemented by MySQL version 5.0.3 or newer with the InnoDB storage engine.
* It's now possible to pass initial values to the model forms that are part of
both model formsets and inline model formsets as returned from factory
functions ``modelformset_factory`` and ``inlineformset_factory`` respectively
just like with regular formsets. However, initial values only apply to extra
forms, i.e. those which are not bound to an existing model instance.
* The sitemaps framework can now handle HTTPS links using the new
:attr:`Sitemap.protocol <django.contrib.sitemaps.Sitemap.protocol>` class
attribute.
* A new :class:`django.test.SimpleTestCase` subclass of
:class:`unittest.TestCase`
that's lighter than :class:`django.test.TestCase` and company. It can be
useful in tests that don't need to hit a database. See
:ref:`testcase_hierarchy_diagram`.
.. _backwards-incompatible-1.4:
Backwards incompatible changes in 1.4
=====================================
SECRET_KEY setting is required
------------------------------
Running Django with an empty or known :setting:`SECRET_KEY` disables many of
Django's security protections and can lead to remote-code-execution
vulnerabilities. No Django site should ever be run without a
:setting:`SECRET_KEY`.
In Django 1.4, starting Django with an empty :setting:`SECRET_KEY` will raise a
`DeprecationWarning`. In Django 1.5, it will raise an exception and Django will
refuse to start. This is slightly accelerated from the usual deprecation path
due to the severity of the consequences of running Django with no
:setting:`SECRET_KEY`.
``django.contrib.admin``
------------------------
The included administration app ``django.contrib.admin`` has for a long time
shipped with a default set of static files such as JavaScript, images and
stylesheets. Django 1.3 added a new contrib app ``django.contrib.staticfiles``
to handle such files in a generic way and defined conventions for static
files included in apps.
Starting in Django 1.4, the admin's static files also follow this
convention, to make the files easier to deploy. In previous versions of Django,
it was also common to define an ``ADMIN_MEDIA_PREFIX`` setting to point to the
URL where the admin's static files live on a Web server. This setting has now
been deprecated and replaced by the more general setting :setting:`STATIC_URL`.
Django will now expect to find the admin static files under the URL
``<STATIC_URL>/admin/``.
If you've previously used a URL path for ``ADMIN_MEDIA_PREFIX`` (e.g.
``/media/``) simply make sure :setting:`STATIC_URL` and :setting:`STATIC_ROOT`
are configured and your Web server serves those files correctly. The
development server continues to serve the admin files just like before. Read
the :doc:`static files howto </howto/static-files/index>` for more details.
If your ``ADMIN_MEDIA_PREFIX`` is set to an specific domain (e.g.
``http://media.example.com/admin/``), make sure to also set your
:setting:`STATIC_URL` setting to the correct URL -- for example,
``http://media.example.com/``.
.. warning::
If you're implicitly relying on the path of the admin static files within
Django's source code, you'll need to update that path. The files were moved
from :file:`django/contrib/admin/media/` to
:file:`django/contrib/admin/static/admin/`.
Supported browsers for the admin
--------------------------------
Django hasn't had a clear policy on which browsers are supported by the
admin app. Our new policy formalizes existing practices: `YUI's A-grade`_
browsers should provide a fully-functional admin experience, with the notable
exception of Internet Explorer 6, which is no longer supported.
Released over 10 years ago, IE6 imposes many limitations on modern Web
development. The practical implications of this policy are that contributors
are free to improve the admin without consideration for these limitations.
Obviously, this new policy **has no impact** on sites you develop using Django.
It only applies to the Django admin. Feel free to develop apps compatible with
any range of browsers.
.. _YUI's A-grade: http://yuilibrary.com/yui/docs/tutorials/gbs/
Removed admin icons
-------------------
As part of an effort to improve the performance and usability of the admin's
change-list sorting interface and :attr:`horizontal
<django.contrib.admin.ModelAdmin.filter_horizontal>` and :attr:`vertical
<django.contrib.admin.ModelAdmin.filter_vertical>` "filter" widgets, some icon
files were removed and grouped into two sprite files.
Specifically: ``selector-add.gif``, ``selector-addall.gif``,
``selector-remove.gif``, ``selector-removeall.gif``,
``selector_stacked-add.gif`` and ``selector_stacked-remove.gif`` were
combined into ``selector-icons.gif``; and ``arrow-up.gif`` and
``arrow-down.gif`` were combined into ``sorting-icons.gif``.
If you used those icons to customize the admin, then you'll need to replace
them with your own icons or get the files from a previous release.
CSS class names in admin forms
------------------------------
To avoid conflicts with other common CSS class names (e.g. "button"), we added
a prefix ("field-") to all CSS class names automatically generated from the
form field names in the main admin forms, stacked inline forms and tabular
inline cells. You'll need to take that prefix into account in your custom
style sheets or JavaScript files if you previously used plain field names as
selectors for custom styles or JavaScript transformations.
Compatibility with old signed data
----------------------------------
Django 1.3 changed the cryptographic signing mechanisms used in a number of
places in Django. While Django 1.3 kept fallbacks that would accept hashes
produced by the previous methods, these fallbacks are removed in Django 1.4.
So, if you upgrade to Django 1.4 directly from 1.2 or earlier, you may
lose/invalidate certain pieces of data that have been cryptographically signed
using an old method. To avoid this, use Django 1.3 first for a period of time
to allow the signed data to expire naturally. The affected parts are detailed
below, with 1) the consequences of ignoring this advice and 2) the amount of
time you need to run Django 1.3 for the data to expire or become irrelevant.
* ``contrib.sessions`` data integrity check
* Consequences: The user will be logged out, and session data will be lost.
* Time period: Defined by :setting:`SESSION_COOKIE_AGE`.
* ``contrib.auth`` password reset hash
* Consequences: Password reset links from before the upgrade will not work.
* Time period: Defined by :setting:`PASSWORD_RESET_TIMEOUT_DAYS`.
Form-related hashes: these have a are much shorter lifetime and are relevant
only for the short window where a user might fill in a form generated by the
pre-upgrade Django instance and try to submit it to the upgraded Django
instance:
* ``contrib.comments`` form security hash
* Consequences: The user will see the validation error "Security hash failed."
* Time period: The amount of time you expect users to take filling out comment
forms.
* ``FormWizard`` security hash
* Consequences: The user will see an error about the form having expired
and will be sent back to the first page of the wizard, losing the data
entered so far.
* Time period: The amount of time you expect users to take filling out the
affected forms.
* CSRF check
* Note: This is actually a Django 1.1 fallback, not Django 1.2,
and it applies only if you're upgrading from 1.1.
* Consequences: The user will see a 403 error with any CSRF-protected POST
form.
* Time period: The amount of time you expect user to take filling out
such forms.
* ``contrib.auth`` user password hash-upgrade sequence
* Consequences: Each user's password will be updated to a stronger password
hash when it's written to the database in 1.4. This means that if you
upgrade to 1.4 and then need to downgrade to 1.3, version 1.3 won't be able
to read the updated passwords.
* Remedy: Set :setting:`PASSWORD_HASHERS` to use your original password
hashing when you initially upgrade to 1.4. After you confirm your app works
well with Django 1.4 and you won't have to roll back to 1.3, enable the new
password hashes.
``django.contrib.flatpages``
----------------------------
Starting in 1.4, the
:class:`~django.contrib.flatpages.middleware.FlatpageFallbackMiddleware` only
adds a trailing slash and redirects if the resulting URL refers to an existing
flatpage. For example, requesting ``/notaflatpageoravalidurl`` in a previous
version would redirect to ``/notaflatpageoravalidurl/``, which would
subsequently raise a 404. Requesting ``/notaflatpageoravalidurl`` now will
immediately raise a 404.
Also, redirects returned by flatpages are now permanent (with 301 status code),
to match the behavior of :class:`~django.middleware.common.CommonMiddleware`.
Serialization of :class:`~datetime.datetime` and :class:`~datetime.time`
------------------------------------------------------------------------
As a consequence of time-zone support, and according to the ECMA-262
specification, we made changes to the JSON serializer:
* It includes the time zone for aware datetime objects. It raises an exception
for aware time objects.
* It includes milliseconds for datetime and time objects. There is still
some precision loss, because Python stores microseconds (6 digits) and JSON
only supports milliseconds (3 digits). However, it's better than discarding
microseconds entirely.
We changed the XML serializer to use the ISO8601 format for datetimes.
The letter ``T`` is used to separate the date part from the time part, instead
of a space. Time zone information is included in the ``[+-]HH:MM`` format.
Though the serializers now use these new formats when creating fixtures, they
can still load fixtures that use the old format.
``supports_timezone`` changed to ``False`` for SQLite
-----------------------------------------------------
The database feature ``supports_timezone`` used to be ``True`` for SQLite.
Indeed, if you saved an aware datetime object, SQLite stored a string that
included an UTC offset. However, this offset was ignored when loading the value
back from the database, which could corrupt the data.
In the context of time-zone support, this flag was changed to ``False``, and
datetimes are now stored without time-zone information in SQLite. When
:setting:`USE_TZ` is ``False``, if you attempt to save an aware datetime
object, Django raises an exception.
``MySQLdb``-specific exceptions
-------------------------------
The MySQL backend historically has raised ``MySQLdb.OperationalError``
when a query triggered an exception. We've fixed this bug, and we now raise
:exc:`django.db.DatabaseError` instead. If you were testing for
``MySQLdb.OperationalError``, you'll need to update your ``except``
clauses.
Database connection's thread-locality
-------------------------------------
``DatabaseWrapper`` objects (i.e. the connection objects referenced by
``django.db.connection`` and ``django.db.connections["some_alias"]``) used to
be thread-local. They are now global objects in order to be potentially shared
between multiple threads. While the individual connection objects are now
global, the ``django.db.connections`` dictionary referencing those objects is
still thread-local. Therefore if you just use the ORM or
``DatabaseWrapper.cursor()`` then the behavior is still the same as before.
Note, however, that ``django.db.connection`` does not directly reference the
default ``DatabaseWrapper`` object anymore and is now a proxy to access that
object's attributes. If you need to access the actual ``DatabaseWrapper``
object, use ``django.db.connections[DEFAULT_DB_ALIAS]`` instead.
As part of this change, all underlying SQLite connections are now enabled for
potential thread-sharing (by passing the ``check_same_thread=False`` attribute
to pysqlite). ``DatabaseWrapper`` however preserves the previous behavior by
disabling thread-sharing by default, so this does not affect any existing
code that purely relies on the ORM or on ``DatabaseWrapper.cursor()``.
Finally, while it's now possible to pass connections between threads, Django
doesn't make any effort to synchronize access to the underlying backend.
Concurrency behavior is defined by the underlying backend implementation.
Check their documentation for details.
`COMMENTS_BANNED_USERS_GROUP` setting
-------------------------------------
Django's comments has historically
supported excluding the comments of a special user group, but we've never
documented the feature properly and didn't enforce the exclusion in other parts
of the app such as the template tags. To fix this problem, we removed the code
from the feed class.
If you rely on the feature and want to restore the old behavior, use a custom
comment model manager to exclude the user group, like this::
from django.conf import settings
from django.contrib.comments.managers import CommentManager
class BanningCommentManager(CommentManager):
def get_query_set(self):
qs = super().get_query_set()
if getattr(settings, 'COMMENTS_BANNED_USERS_GROUP', None):
where = ['user_id NOT IN (SELECT user_id FROM auth_user_groups WHERE group_id = %s)']
params = [settings.COMMENTS_BANNED_USERS_GROUP]
qs = qs.extra(where=where, params=params)
return qs
Save this model manager in your custom comment app (e.g., in
``my_comments_app/managers.py``) and add it your custom comment app model::
from django.db import models
from django.contrib.comments.models import Comment
from my_comments_app.managers import BanningCommentManager
class CommentWithTitle(Comment):
title = models.CharField(max_length=300)
objects = BanningCommentManager()
`IGNORABLE_404_STARTS` and `IGNORABLE_404_ENDS` settings
--------------------------------------------------------
Until Django 1.3, it was possible to exclude some URLs from Django's
:doc:`404 error reporting</howto/error-reporting>` by adding prefixes to
``IGNORABLE_404_STARTS`` and suffixes to ``IGNORABLE_404_ENDS``.
In Django 1.4, these two settings are superseded by
:setting:`IGNORABLE_404_URLS`, which is a list of compiled regular
expressions. Django won't send an email for 404 errors on URLs that match any
of them.
Furthermore, the previous settings had some rather arbitrary default values::
IGNORABLE_404_STARTS = ('/cgi-bin/', '/_vti_bin', '/_vti_inf')
IGNORABLE_404_ENDS = ('mail.pl', 'mailform.pl', 'mail.cgi', 'mailform.cgi',
'favicon.ico', '.php')
It's not Django's role to decide if your website has a legacy ``/cgi-bin/``
section or a ``favicon.ico``. As a consequence, the default values of
:setting:`IGNORABLE_404_URLS`, ``IGNORABLE_404_STARTS``, and
``IGNORABLE_404_ENDS`` are all now empty.
If you have customized ``IGNORABLE_404_STARTS`` or ``IGNORABLE_404_ENDS``, or
if you want to keep the old default value, you should add the following lines
in your settings file::
import re
IGNORABLE_404_URLS = (
# for each <prefix> in IGNORABLE_404_STARTS
re.compile(r'^<prefix>'),
# for each <suffix> in IGNORABLE_404_ENDS
re.compile(r'<suffix>$'),
)
Don't forget to escape characters that have a special meaning in a regular
expression, such as periods.
CSRF protection extended to PUT and DELETE
------------------------------------------
Previously, Django's :doc:`CSRF protection </ref/csrf/>` provided
protection only against POST requests. Since use of PUT and DELETE methods in
AJAX applications is becoming more common, we now protect all methods not
defined as safe by :rfc:`2616` -- i.e., we exempt GET, HEAD, OPTIONS and TRACE,
and we enforce protection on everything else.
If you're using PUT or DELETE methods in AJAX applications, please see the
:ref:`instructions about using AJAX and CSRF <csrf-ajax>`.