1.4.txt 57 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350
  1. ========================
  2. Django 1.4 release notes
  3. ========================
  4. *March 23, 2012*
  5. Welcome to Django 1.4!
  6. These release notes cover the `new features`_, as well
  7. as some `backwards incompatible changes`_ you'll want to be aware of
  8. when upgrading from Django 1.3 or older versions. We've also dropped some
  9. features, which are detailed in :doc:`our deprecation plan
  10. </internals/deprecation>`, and we've `begun the deprecation process for some
  11. features`_.
  12. .. _`new features`: `What's new in Django 1.4`_
  13. .. _`backwards incompatible changes`: `Backwards incompatible changes in 1.4`_
  14. .. _`begun the deprecation process for some features`: `Features deprecated in 1.4`_
  15. Overview
  16. ========
  17. The biggest new feature in Django 1.4 is `support for time zones`_ when
  18. handling date/times. When enabled, this Django will store date/times in UTC,
  19. use timezone-aware objects internally, and translate them to users' local
  20. timezones for display.
  21. If you're upgrading an existing project to Django 1.4, switching to the time-
  22. zone aware mode may take some care: the new mode disallows some rather sloppy
  23. behavior that used to be accepted. We encourage anyone who's upgrading to check
  24. out the :ref:`timezone migration guide <time-zones-migration-guide>` and the
  25. :ref:`timezone FAQ <time-zones-faq>` for useful pointers.
  26. Other notable new features in Django 1.4 include:
  27. * A number of ORM improvements, including `SELECT FOR UPDATE support`_,
  28. the ability to `bulk insert <#model-objects-bulk-create-in-the-orm>`_
  29. large datasets for improved performance, and
  30. `QuerySet.prefetch_related`_, a method to batch-load related objects
  31. in areas where :meth:`~django.db.models.query.QuerySet.select_related`
  32. doesn't work.
  33. * Some nice security additions, including `improved password hashing`_
  34. (featuring PBKDF2_ and bcrypt_ support), new `tools for cryptographic
  35. signing`_, several `CSRF improvements`_, and `simple clickjacking
  36. protection`_.
  37. * An `updated default project layout and manage.py`_ that removes the "magic"
  38. from prior versions. And for those who don't like the new layout, you can
  39. use `custom project and app templates`_ instead!
  40. * `Support for in-browser testing frameworks`_ (like Selenium_).
  41. * ... and a whole lot more; `see below <#what-s-new-in-django-1-4>`_!
  42. Wherever possible we try to introduce new features in a backwards-compatible
  43. manner per :doc:`our API stability policy </misc/api-stability>` policy.
  44. However, as with previous releases, Django 1.4 ships with some minor
  45. `backwards incompatible changes`_; people upgrading from previous versions
  46. of Django should read that list carefully.
  47. Python compatibility
  48. ====================
  49. Django 1.4 has dropped support for Python 2.4. Python 2.5 is now the minimum
  50. required Python version. Django is tested and supported on Python 2.5, 2.6 and
  51. 2.7.
  52. This change should affect only a small number of Django users, as most
  53. operating-system vendors today are shipping Python 2.5 or newer as their default
  54. version. If you're still using Python 2.4, however, you'll need to stick to
  55. Django 1.3 until you can upgrade. Per :doc:`our support policy
  56. </internals/release-process>`, Django 1.3 will continue to receive security
  57. support until the release of Django 1.5.
  58. Django does not support Python 3.x at this time. At some point before the
  59. release of Django 1.4, we plan to publish a document outlining our full
  60. timeline for deprecating Python 2.x and moving to Python 3.x.
  61. What's new in Django 1.4
  62. ========================
  63. Support for time zones
  64. ~~~~~~~~~~~~~~~~~~~~~~
  65. In previous versions, Django used "naive" date/times (that is, date/times
  66. without an associated time zone), leaving it up to each developer to interpret
  67. what a given date/time "really means". This can cause all sorts of subtle
  68. timezone-related bugs.
  69. In Django 1.4, you can now switch Django into a more correct, time-zone aware
  70. mode. In this mode, Django stores date and time information in UTC in the
  71. database, uses time-zone-aware datetime objects internally and translates them
  72. to the end user's time zone in templates and forms. Reasons for using this
  73. feature include:
  74. - Customizing date and time display for users around the world.
  75. - Storing datetimes in UTC for database portability and interoperability.
  76. (This argument doesn't apply to PostgreSQL, because it already stores
  77. timestamps with time zone information in Django 1.3.)
  78. - Avoiding data corruption problems around DST transitions.
  79. Time zone support is enabled by default in new projects created with
  80. :djadmin:`startproject`. If you want to use this feature in an existing
  81. project, read the :ref:`migration guide <time-zones-migration-guide>`. If you
  82. encounter problems, there's a helpful :ref:`FAQ <time-zones-faq>`.
  83. Support for in-browser testing frameworks
  84. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  85. Django 1.4 supports integration with in-browser testing frameworks like
  86. Selenium_. The new :class:`django.test.LiveServerTestCase` base class lets you
  87. test the interactions between your site's front and back ends more
  88. comprehensively. See the
  89. :class:`documentation<django.test.LiveServerTestCase>` for more details and
  90. concrete examples.
  91. .. _Selenium: http://seleniumhq.org/
  92. Updated default project layout and ``manage.py``
  93. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  94. Django 1.4 ships with an updated default project layout and ``manage.py`` file
  95. for the :djadmin:`startproject` management command. These fix some issues with
  96. the previous ``manage.py`` handling of Python import paths that caused double
  97. imports, trouble moving from development to deployment, and other
  98. difficult-to-debug path issues.
  99. The previous ``manage.py`` called functions that are now deprecated, and thus
  100. projects upgrading to Django 1.4 should update their ``manage.py``. (The
  101. old-style ``manage.py`` will continue to work as before until Django 1.6. In
  102. 1.5 it will raise ``DeprecationWarning``).
  103. The new recommended ``manage.py`` file should look like this::
  104. #!/usr/bin/env python
  105. import os, sys
  106. if __name__ == "__main__":
  107. os.environ.setdefault("DJANGO_SETTINGS_MODULE", "{{ project_name }}.settings")
  108. from django.core.management import execute_from_command_line
  109. execute_from_command_line(sys.argv)
  110. ``{{ project_name }}`` should be replaced with the Python package name of the
  111. actual project.
  112. If settings, URLconfs and apps within the project are imported or referenced
  113. using the project name prefix (e.g. ``myproject.settings``, ``ROOT_URLCONF =
  114. "myproject.urls"``, etc), the new ``manage.py`` will need to be moved one
  115. directory up, so it is outside the project package rather than adjacent to
  116. ``settings.py`` and ``urls.py``.
  117. For instance, with the following layout::
  118. manage.py
  119. mysite/
  120. __init__.py
  121. settings.py
  122. urls.py
  123. myapp/
  124. __init__.py
  125. models.py
  126. You could import ``mysite.settings``, ``mysite.urls``, and ``mysite.myapp``,
  127. but not ``settings``, ``urls``, or ``myapp`` as top-level modules.
  128. Anything imported as a top-level module can be placed adjacent to the new
  129. ``manage.py``. For instance, to decouple "myapp" from the project module and
  130. import it as just ``myapp``, place it outside the ``mysite/`` directory::
  131. manage.py
  132. myapp/
  133. __init__.py
  134. models.py
  135. mysite/
  136. __init__.py
  137. settings.py
  138. urls.py
  139. If the same code is imported inconsistently (some places with the project
  140. prefix, some places without it), the imports will need to be cleaned up when
  141. switching to the new ``manage.py``.
  142. Custom project and app templates
  143. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  144. The :djadmin:`startapp` and :djadmin:`startproject` management commands
  145. now have a ``--template`` option for specifying a path or URL to a custom app
  146. or project template.
  147. For example, Django will use the ``/path/to/my_project_template`` directory
  148. when you run the following command::
  149. django-admin.py startproject --template=/path/to/my_project_template myproject
  150. You can also now provide a destination directory as the second
  151. argument to both :djadmin:`startapp` and :djadmin:`startproject`::
  152. django-admin.py startapp myapp /path/to/new/app
  153. django-admin.py startproject myproject /path/to/new/project
  154. For more information, see the :djadmin:`startapp` and :djadmin:`startproject`
  155. documentation.
  156. Improved WSGI support
  157. ~~~~~~~~~~~~~~~~~~~~~
  158. The :djadmin:`startproject` management command now adds a :file:`wsgi.py`
  159. module to the initial project layout, containing a simple WSGI application that
  160. can be used for :doc:`deploying with WSGI app
  161. servers</howto/deployment/wsgi/index>`.
  162. The :djadmin:`built-in development server<runserver>` now supports using an
  163. externally-defined WSGI callable, which makes it possible to run runserver
  164. with the same WSGI configuration that is used for deployment. The new
  165. :setting:`WSGI_APPLICATION` setting lets you configure which WSGI callable
  166. :djadmin:`runserver` uses.
  167. (The :djadmin:`runfcgi` management command also internally wraps the WSGI
  168. callable configured via :setting:`WSGI_APPLICATION`.)
  169. ``SELECT FOR UPDATE`` support
  170. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  171. Django 1.4 includes a :meth:`QuerySet.select_for_update()
  172. <django.db.models.query.QuerySet.select_for_update>` method, which generates a
  173. ``SELECT ... FOR UPDATE`` SQL query. This will lock rows until the end of the
  174. transaction, meaning other transactions cannot modify or delete rows matched by
  175. a ``FOR UPDATE`` query.
  176. For more details, see the documentation for
  177. :meth:`~django.db.models.query.QuerySet.select_for_update`.
  178. ``Model.objects.bulk_create`` in the ORM
  179. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  180. This method lets you create multiple objects more efficiently. It can result in
  181. significant performance increases if you have many objects.
  182. Django makes use of this internally, meaning some operations (such as database
  183. setup for test suites) have seen a performance benefit as a result.
  184. See the :meth:`~django.db.models.query.QuerySet.bulk_create` docs for more
  185. information.
  186. ``QuerySet.prefetch_related``
  187. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  188. Similar to :meth:`~django.db.models.query.QuerySet.select_related` but with a
  189. different strategy and broader scope,
  190. :meth:`~django.db.models.query.QuerySet.prefetch_related` has been added to
  191. :class:`~django.db.models.query.QuerySet`. This method returns a new
  192. ``QuerySet`` that will prefetch each of the specified related lookups in a
  193. single batch as soon as the query begins to be evaluated. Unlike
  194. ``select_related``, it does the joins in Python, not in the database, and
  195. supports many-to-many relationships,
  196. :class:`~django.contrib.contenttypes.generic.GenericForeignKey` and more. This
  197. allows you to fix a very common performance problem in which your code ends up
  198. doing O(n) database queries (or worse) if objects on your primary ``QuerySet``
  199. each have many related objects that you also need to fetch.
  200. Improved password hashing
  201. ~~~~~~~~~~~~~~~~~~~~~~~~~
  202. Django's auth system (``django.contrib.auth``) stores passwords using a one-way
  203. algorithm. Django 1.3 uses the SHA1_ algorithm, but increasing processor speeds
  204. and theoretical attacks have revealed that SHA1 isn't as secure as we'd like.
  205. Thus, Django 1.4 introduces a new password storage system: by default Django now
  206. uses the PBKDF2_ algorithm (as recommended by NIST_). You can also easily choose
  207. a different algorithm (including the popular bcrypt_ algorithm). For more
  208. details, see :ref:`auth_password_storage`.
  209. .. _sha1: http://en.wikipedia.org/wiki/SHA1
  210. .. _pbkdf2: http://en.wikipedia.org/wiki/PBKDF2
  211. .. _nist: http://csrc.nist.gov/publications/nistpubs/800-132/nist-sp800-132.pdf
  212. .. _bcrypt: http://en.wikipedia.org/wiki/Bcrypt
  213. HTML5 doctype
  214. ~~~~~~~~~~~~~
  215. We've switched the admin and other bundled templates to use the HTML5
  216. doctype. While Django will be careful to maintain compatibility with older
  217. browsers, this change means that you can use any HTML5 features you need in
  218. admin pages without having to lose HTML validity or override the provided
  219. templates to change the doctype.
  220. List filters in admin interface
  221. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  222. Prior to Django 1.4, the :mod:`~django.contrib.admin` app let you specify
  223. change list filters by specifying a field lookup, but it didn't allow you to
  224. create custom filters. This has been rectified with a simple API (previously
  225. used internally and known as "FilterSpec"). For more details, see the
  226. documentation for :attr:`~django.contrib.admin.ModelAdmin.list_filter`.
  227. Multiple sort in admin interface
  228. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  229. The admin change list now supports sorting on multiple columns. It respects all
  230. elements of the :attr:`~django.contrib.admin.ModelAdmin.ordering` attribute, and
  231. sorting on multiple columns by clicking on headers is designed to mimic the
  232. behavior of desktop GUIs. We also added a
  233. :meth:`~django.contrib.admin.ModelAdmin.get_ordering` method for specifying the
  234. ordering dynamically (i.e., depending on the request).
  235. New ``ModelAdmin`` methods
  236. ~~~~~~~~~~~~~~~~~~~~~~~~~~
  237. We added a :meth:`~django.contrib.admin.ModelAdmin.save_related` method to
  238. :mod:`~django.contrib.admin.ModelAdmin` to ease customization of how
  239. related objects are saved in the admin.
  240. Two other new :class:`~django.contrib.admin.ModelAdmin` methods,
  241. :meth:`~django.contrib.admin.ModelAdmin.get_list_display` and
  242. :meth:`~django.contrib.admin.ModelAdmin.get_list_display_links`
  243. enable dynamic customization of fields and links displayed on the admin
  244. change list.
  245. Admin inlines respect user permissions
  246. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  247. Admin inlines now only allow those actions for which the user has
  248. permission. For ``ManyToMany`` relationships with an auto-created intermediate
  249. model (which does not have its own permissions), the change permission for the
  250. related model determines if the user has the permission to add, change or
  251. delete relationships.
  252. Tools for cryptographic signing
  253. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  254. Django 1.4 adds both a low-level API for signing values and a high-level API
  255. for setting and reading signed cookies, one of the most common uses of
  256. signing in Web applications.
  257. See the :doc:`cryptographic signing </topics/signing>` docs for more
  258. information.
  259. Cookie-based session backend
  260. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  261. Django 1.4 introduces a cookie-based session backend that uses the tools for
  262. :doc:`cryptographic signing </topics/signing>` to store the session data in
  263. the client's browser.
  264. .. warning::
  265. Session data is signed and validated by the server, but it's not
  266. encrypted. This means a user can view any data stored in the
  267. session but cannot change it. Please read the documentation for
  268. further clarification before using this backend.
  269. See the :ref:`cookie-based session backend <cookie-session-backend>` docs for
  270. more information.
  271. New form wizard
  272. ~~~~~~~~~~~~~~~
  273. The previous ``FormWizard`` from :mod:`django.contrib.formtools` has been
  274. replaced with a new implementation based on the class-based views
  275. introduced in Django 1.3. It features a pluggable storage API and doesn't
  276. require the wizard to pass around hidden fields for every previous step.
  277. Django 1.4 ships with a session-based storage backend and a cookie-based
  278. storage backend. The latter uses the tools for
  279. :doc:`cryptographic signing </topics/signing>` also introduced in
  280. Django 1.4 to store the wizard's state in the user's cookies.
  281. See the :doc:`form wizard </ref/contrib/formtools/form-wizard>` docs for
  282. more information.
  283. ``reverse_lazy``
  284. ~~~~~~~~~~~~~~~~
  285. A lazily evaluated version of :func:`django.core.urlresolvers.reverse` was
  286. added to allow using URL reversals before the project's URLconf gets loaded.
  287. Translating URL patterns
  288. ~~~~~~~~~~~~~~~~~~~~~~~~
  289. Django can now look for a language prefix in the URLpattern when using the new
  290. :func:`~django.conf.urls.i18n.i18n_patterns` helper function.
  291. It's also now possible to define translatable URL patterns using
  292. :func:`~django.utils.translation.ugettext_lazy`. See
  293. :ref:`url-internationalization` for more information about the language prefix
  294. and how to internationalize URL patterns.
  295. Contextual translation support for ``{% trans %}`` and ``{% blocktrans %}``
  296. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  297. The :ref:`contextual translation<contextual-markers>` support introduced in
  298. Django 1.3 via the ``pgettext`` function has been extended to the
  299. :ttag:`trans` and :ttag:`blocktrans` template tags using the new ``context``
  300. keyword.
  301. Customizable ``SingleObjectMixin`` URLConf kwargs
  302. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  303. Two new attributes,
  304. :attr:`pk_url_kwarg<django.views.generic.detail.SingleObjectMixin.pk_url_kwarg>`
  305. and
  306. :attr:`slug_url_kwarg<django.views.generic.detail.SingleObjectMixin.slug_url_kwarg>`,
  307. have been added to :class:`~django.views.generic.detail.SingleObjectMixin` to
  308. enable the customization of URLconf keyword arguments used for single
  309. object generic views.
  310. Assignment template tags
  311. ~~~~~~~~~~~~~~~~~~~~~~~~
  312. A new :ref:`assignment_tag<howto-custom-template-tags-assignment-tags>` helper
  313. function was added to ``template.Library`` to ease the creation of template
  314. tags that store data in a specified context variable.
  315. ``*args`` and ``**kwargs`` support for template tag helper functions
  316. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  317. The :ref:`simple_tag<howto-custom-template-tags-simple-tags>`,
  318. :ref:`inclusion_tag <howto-custom-template-tags-inclusion-tags>` and
  319. newly introduced
  320. :ref:`assignment_tag<howto-custom-template-tags-assignment-tags>` template
  321. helper functions may now accept any number of positional or keyword arguments.
  322. For example:
  323. .. code-block:: python
  324. @register.simple_tag
  325. def my_tag(a, b, *args, **kwargs):
  326. warning = kwargs['warning']
  327. profile = kwargs['profile']
  328. ...
  329. return ...
  330. Then, in the template, any number of arguments may be passed to the template tag.
  331. For example:
  332. .. code-block:: html+django
  333. {% my_tag 123 "abcd" book.title warning=message|lower profile=user.profile %}
  334. No wrapping of exceptions in ``TEMPLATE_DEBUG`` mode
  335. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  336. In previous versions of Django, whenever the :setting:`TEMPLATE_DEBUG` setting
  337. was ``True``, any exception raised during template rendering (even exceptions
  338. unrelated to template syntax) were wrapped in ``TemplateSyntaxError`` and
  339. re-raised. This was done in order to provide detailed template source location
  340. information in the debug 500 page.
  341. In Django 1.4, exceptions are no longer wrapped. Instead, the original
  342. exception is annotated with the source information. This means that catching
  343. exceptions from template rendering is now consistent regardless of the value of
  344. :setting:`TEMPLATE_DEBUG`, and there's no need to catch and unwrap
  345. ``TemplateSyntaxError`` in order to catch other errors.
  346. ``truncatechars`` template filter
  347. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  348. This new filter truncates a string to be no longer than the specified
  349. number of characters. Truncated strings end with a translatable ellipsis
  350. sequence ("..."). See the documentation for :tfilter:`truncatechars` for
  351. more details.
  352. ``static`` template tag
  353. ~~~~~~~~~~~~~~~~~~~~~~~
  354. The :mod:`staticfiles<django.contrib.staticfiles>` contrib app has a new
  355. :ttag:`static<staticfiles-static>` template tag to refer to files saved with
  356. the :setting:`STATICFILES_STORAGE` storage backend. It uses the storage
  357. backend's ``url`` method and therefore supports advanced features such as
  358. :ref:`serving files from a cloud service<staticfiles-from-cdn>`.
  359. ``CachedStaticFilesStorage`` storage backend
  360. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  361. The :mod:`staticfiles<django.contrib.staticfiles>` contrib app now has a
  362. :class:`~django.contrib.staticfiles.storage.CachedStaticFilesStorage` backend
  363. that caches the files it saves (when running the :djadmin:`collectstatic`
  364. management command) by appending the MD5 hash of the file's content to the
  365. filename. For example, the file ``css/styles.css`` would also be saved as
  366. ``css/styles.55e7cbb9ba48.css``
  367. See the :class:`~django.contrib.staticfiles.storage.CachedStaticFilesStorage`
  368. docs for more information.
  369. Simple clickjacking protection
  370. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  371. We've added a middleware to provide easy protection against `clickjacking
  372. <http://en.wikipedia.org/wiki/Clickjacking>`_ using the ``X-Frame-Options``
  373. header. It's not enabled by default for backwards compatibility reasons, but
  374. you'll almost certainly want to :doc:`enable it </ref/clickjacking/>` to help
  375. plug that security hole for browsers that support the header.
  376. CSRF improvements
  377. ~~~~~~~~~~~~~~~~~
  378. We've made various improvements to our CSRF features, including the
  379. :func:`~django.views.decorators.csrf.ensure_csrf_cookie` decorator, which can
  380. help with AJAX-heavy sites; protection for PUT and DELETE requests; and the
  381. :setting:`CSRF_COOKIE_SECURE` and :setting:`CSRF_COOKIE_PATH` settings, which can
  382. improve the security and usefulness of CSRF protection. See the :doc:`CSRF
  383. docs </ref/contrib/csrf>` for more information.
  384. Error report filtering
  385. ~~~~~~~~~~~~~~~~~~~~~~
  386. We added two function decorators, :func:`sensitive_variables` and
  387. :func:`sensitive_post_parameters`, to allow designating the local variables
  388. and POST parameters that may contain sensitive information and should be
  389. filtered out of error reports.
  390. All POST parameters are now systematically filtered out of error reports for
  391. certain views (``login``, ``password_reset_confirm``, ``password_change`` and
  392. ``add_view`` in :mod:`django.contrib.auth.views`, as well as
  393. ``user_change_password`` in the admin app) to prevent the leaking of sensitive
  394. information such as user passwords.
  395. You can override or customize the default filtering by writing a :ref:`custom
  396. filter<custom-error-reports>`. For more information see the docs on
  397. :ref:`Filtering error reports<filtering-error-reports>`.
  398. Extended IPv6 support
  399. ~~~~~~~~~~~~~~~~~~~~~
  400. Django 1.4 can now better handle IPv6 addresses with the new
  401. :class:`~django.db.models.GenericIPAddressField` model field,
  402. :class:`~django.forms.GenericIPAddressField` form field and
  403. the validators :data:`~django.core.validators.validate_ipv46_address` and
  404. :data:`~django.core.validators.validate_ipv6_address`.
  405. HTML comparisons in tests
  406. ~~~~~~~~~~~~~~~~~~~~~~~~~
  407. The base classes in :mod:`django.test` now have some helpers to
  408. compare HTML without tripping over irrelevant differences in whitespace,
  409. argument quoting/ordering and closing of self-closing tags. You can either
  410. compare HTML directly with the new
  411. :meth:`~django.test.SimpleTestCase.assertHTMLEqual` and
  412. :meth:`~django.test.SimpleTestCase.assertHTMLNotEqual` assertions, or use
  413. the ``html=True`` flag with
  414. :meth:`~django.test.TestCase.assertContains` and
  415. :meth:`~django.test.TestCase.assertNotContains` to test whether the
  416. client's response contains a given HTML fragment. See the :ref:`assertions
  417. documentation <assertions>` for more.
  418. Two new date format strings
  419. ~~~~~~~~~~~~~~~~~~~~~~~~~~~
  420. Two new :tfilter:`date` formats were added for use in template filters,
  421. template tags and :ref:`format-localization`:
  422. - ``e`` -- the name of the timezone of the given datetime object
  423. - ``o`` -- the ISO 8601 year number
  424. Please make sure to update your :ref:`custom format files
  425. <custom-format-files>` if they contain either ``e`` or ``o`` in a format
  426. string. For example a Spanish localization format previously only escaped the
  427. ``d`` format character::
  428. DATE_FORMAT = r'j \de F \de Y'
  429. But now it needs to also escape ``e`` and ``o``::
  430. DATE_FORMAT = r'j \d\e F \d\e Y'
  431. For more information, see the :tfilter:`date` documentation.
  432. Minor features
  433. ~~~~~~~~~~~~~~
  434. Django 1.4 also includes several smaller improvements worth noting:
  435. * A more usable stacktrace in the technical 500 page. Frames in the
  436. stack trace that reference Django's framework code are dimmed out,
  437. while frames in application code are slightly emphasized. This change
  438. makes it easier to scan a stacktrace for issues in application code.
  439. * :doc:`Tablespace support </topics/db/tablespaces>` in PostgreSQL.
  440. * Customizable names for :meth:`~django.template.Library.simple_tag`.
  441. * In the documentation, a helpful :doc:`security overview </topics/security>`
  442. page.
  443. * The ``django.contrib.auth.models.check_password`` function has been moved
  444. to the :mod:`django.contrib.auth.hashers` module. Importing it from the old
  445. location will still work, but you should update your imports.
  446. * The :djadmin:`collectstatic` management command now has a ``--clear`` option
  447. to delete all files at the destination before copying or linking the static
  448. files.
  449. * It's now possible to load fixtures containing forward references when using
  450. MySQL with the InnoDB database engine.
  451. * A new 403 response handler has been added as
  452. ``'django.views.defaults.permission_denied'``. You can set your own handler by
  453. setting the value of :data:`django.conf.urls.handler403`. See the
  454. documentation about :ref:`the 403 (HTTP Forbidden) view<http_forbidden_view>`
  455. for more information.
  456. * The :djadmin:`makemessages` command uses a new and more accurate lexer,
  457. `JsLex`_, for extracting translatable strings from JavaScript files.
  458. .. _JsLex: https://bitbucket.org/ned/jslex
  459. * The :ttag:`trans` template tag now takes an optional ``as`` argument to
  460. be able to retrieve a translation string without displaying it but setting
  461. a template context variable instead.
  462. * The :ttag:`if` template tag now supports ``{% elif %}`` clauses.
  463. * If your Django app is behind a proxy, you might find the new
  464. :setting:`SECURE_PROXY_SSL_HEADER` setting useful. It solves the problem of your
  465. proxy "eating" the fact that a request came in via HTTPS. But only use this
  466. setting if you know what you're doing.
  467. * A new, plain-text, version of the HTTP 500 status code internal error page
  468. served when :setting:`DEBUG` is ``True`` is now sent to the client when
  469. Django detects that the request has originated in JavaScript code.
  470. (:meth:`~django.http.HttpRequest.is_ajax` is used for this.)
  471. Like its HTML counterpart, it contains a collection of different
  472. pieces of information about the state of the application.
  473. This should make it easier to read when debugging interaction with
  474. client-side JavaScript.
  475. * Added the :djadminopt:`--no-location` option to the :djadmin:`makemessages`
  476. command.
  477. * Changed the ``locmem`` cache backend to use
  478. ``pickle.HIGHEST_PROTOCOL`` for better compatibility with the other
  479. cache backends.
  480. * Added support in the ORM for generating ``SELECT`` queries containing
  481. ``DISTINCT ON``.
  482. The ``distinct()`` ``QuerySet`` method now accepts an optional list of model
  483. field names. If specified, then the ``DISTINCT`` statement is limited to these
  484. fields. This is only supported in PostgreSQL.
  485. For more details, see the documentation for
  486. :meth:`~django.db.models.query.QuerySet.distinct`.
  487. * The admin login page will add a password reset link if you include a URL with
  488. the name `'admin_password_reset'` in your urls.py, so plugging in the built-in
  489. password reset mechanism and making it available is now much easier. For
  490. details, see :ref:`auth_password_reset`.
  491. * The MySQL database backend can now make use of the savepoint feature
  492. implemented by MySQL version 5.0.3 or newer with the InnoDB storage engine.
  493. * It's now possible to pass initial values to the model forms that are part of
  494. both model formsets and inline model formsets as returned from factory
  495. functions ``modelformset_factory`` and ``inlineformset_factory`` respectively
  496. just like with regular formsets. However, initial values only apply to extra
  497. forms, i.e. those which are not bound to an existing model instance.
  498. * The sitemaps framework can now handle HTTPS links using the new
  499. :attr:`Sitemap.protocol <django.contrib.sitemaps.Sitemap.protocol>` class
  500. attribute.
  501. * A new :class:`django.test.SimpleTestCase` subclass of
  502. :class:`unittest.TestCase`
  503. that's lighter than :class:`django.test.TestCase` and company. It can be
  504. useful in tests that don't need to hit a database. See
  505. :ref:`testcase_hierarchy_diagram`.
  506. Backwards incompatible changes in 1.4
  507. =====================================
  508. SECRET_KEY setting is required
  509. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  510. Running Django with an empty or known :setting:`SECRET_KEY` disables many of
  511. Django's security protections and can lead to remote-code-execution
  512. vulnerabilities. No Django site should ever be run without a
  513. :setting:`SECRET_KEY`.
  514. In Django 1.4, starting Django with an empty :setting:`SECRET_KEY` will raise a
  515. `DeprecationWarning`. In Django 1.5, it will raise an exception and Django will
  516. refuse to start. This is slightly accelerated from the usual deprecation path
  517. due to the severity of the consequences of running Django with no
  518. :setting:`SECRET_KEY`.
  519. django.contrib.admin
  520. ~~~~~~~~~~~~~~~~~~~~
  521. The included administration app ``django.contrib.admin`` has for a long time
  522. shipped with a default set of static files such as JavaScript, images and
  523. stylesheets. Django 1.3 added a new contrib app ``django.contrib.staticfiles``
  524. to handle such files in a generic way and defined conventions for static
  525. files included in apps.
  526. Starting in Django 1.4, the admin's static files also follow this
  527. convention, to make the files easier to deploy. In previous versions of Django,
  528. it was also common to define an ``ADMIN_MEDIA_PREFIX`` setting to point to the
  529. URL where the admin's static files live on a Web server. This setting has now
  530. been deprecated and replaced by the more general setting :setting:`STATIC_URL`.
  531. Django will now expect to find the admin static files under the URL
  532. ``<STATIC_URL>/admin/``.
  533. If you've previously used a URL path for ``ADMIN_MEDIA_PREFIX`` (e.g.
  534. ``/media/``) simply make sure :setting:`STATIC_URL` and :setting:`STATIC_ROOT`
  535. are configured and your Web server serves those files correctly. The
  536. development server continues to serve the admin files just like before. Read
  537. the :doc:`static files howto </howto/static-files/index>` for more details.
  538. If your ``ADMIN_MEDIA_PREFIX`` is set to an specific domain (e.g.
  539. ``http://media.example.com/admin/``), make sure to also set your
  540. :setting:`STATIC_URL` setting to the correct URL -- for example,
  541. ``http://media.example.com/``.
  542. .. warning::
  543. If you're implicitly relying on the path of the admin static files within
  544. Django's source code, you'll need to update that path. The files were moved
  545. from :file:`django/contrib/admin/media/` to
  546. :file:`django/contrib/admin/static/admin/`.
  547. Supported browsers for the admin
  548. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  549. Django hasn't had a clear policy on which browsers are supported by the
  550. admin app. Our new policy formalizes existing practices: `YUI's A-grade`_
  551. browsers should provide a fully-functional admin experience, with the notable
  552. exception of Internet Explorer 6, which is no longer supported.
  553. Released over 10 years ago, IE6 imposes many limitations on modern Web
  554. development. The practical implications of this policy are that contributors
  555. are free to improve the admin without consideration for these limitations.
  556. Obviously, this new policy **has no impact** on sites you develop using Django.
  557. It only applies to the Django admin. Feel free to develop apps compatible with
  558. any range of browsers.
  559. .. _YUI's A-grade: http://yuilibrary.com/yui/docs/tutorials/gbs/
  560. Removed admin icons
  561. ~~~~~~~~~~~~~~~~~~~
  562. As part of an effort to improve the performance and usability of the admin's
  563. change-list sorting interface and :attr:`horizontal
  564. <django.contrib.admin.ModelAdmin.filter_horizontal>` and :attr:`vertical
  565. <django.contrib.admin.ModelAdmin.filter_vertical>` "filter" widgets, some icon
  566. files were removed and grouped into two sprite files.
  567. Specifically: ``selector-add.gif``, ``selector-addall.gif``,
  568. ``selector-remove.gif``, ``selector-removeall.gif``,
  569. ``selector_stacked-add.gif`` and ``selector_stacked-remove.gif`` were
  570. combined into ``selector-icons.gif``; and ``arrow-up.gif`` and
  571. ``arrow-down.gif`` were combined into ``sorting-icons.gif``.
  572. If you used those icons to customize the admin, then you'll need to replace
  573. them with your own icons or get the files from a previous release.
  574. CSS class names in admin forms
  575. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  576. To avoid conflicts with other common CSS class names (e.g. "button"), we added
  577. a prefix ("field-") to all CSS class names automatically generated from the
  578. form field names in the main admin forms, stacked inline forms and tabular
  579. inline cells. You'll need to take that prefix into account in your custom
  580. style sheets or JavaScript files if you previously used plain field names as
  581. selectors for custom styles or JavaScript transformations.
  582. Compatibility with old signed data
  583. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  584. Django 1.3 changed the cryptographic signing mechanisms used in a number of
  585. places in Django. While Django 1.3 kept fallbacks that would accept hashes
  586. produced by the previous methods, these fallbacks are removed in Django 1.4.
  587. So, if you upgrade to Django 1.4 directly from 1.2 or earlier, you may
  588. lose/invalidate certain pieces of data that have been cryptographically signed
  589. using an old method. To avoid this, use Django 1.3 first for a period of time
  590. to allow the signed data to expire naturally. The affected parts are detailed
  591. below, with 1) the consequences of ignoring this advice and 2) the amount of
  592. time you need to run Django 1.3 for the data to expire or become irrelevant.
  593. * ``contrib.sessions`` data integrity check
  594. * Consequences: The user will be logged out, and session data will be lost.
  595. * Time period: Defined by :setting:`SESSION_COOKIE_AGE`.
  596. * ``contrib.auth`` password reset hash
  597. * Consequences: Password reset links from before the upgrade will not work.
  598. * Time period: Defined by :setting:`PASSWORD_RESET_TIMEOUT_DAYS`.
  599. Form-related hashes: these have a are much shorter lifetime and are relevant
  600. only for the short window where a user might fill in a form generated by the
  601. pre-upgrade Django instance and try to submit it to the upgraded Django
  602. instance:
  603. * ``contrib.comments`` form security hash
  604. * Consequences: The user will see the validation error "Security hash failed."
  605. * Time period: The amount of time you expect users to take filling out comment
  606. forms.
  607. * ``FormWizard`` security hash
  608. * Consequences: The user will see an error about the form having expired
  609. and will be sent back to the first page of the wizard, losing the data
  610. he has entered so far.
  611. * Time period: The amount of time you expect users to take filling out the
  612. affected forms.
  613. * CSRF check
  614. * Note: This is actually a Django 1.1 fallback, not Django 1.2,
  615. and it applies only if you're upgrading from 1.1.
  616. * Consequences: The user will see a 403 error with any CSRF-protected POST
  617. form.
  618. * Time period: The amount of time you expect user to take filling out
  619. such forms.
  620. * ``contrib.auth`` user password hash-upgrade sequence
  621. * Consequences: Each user's password will be updated to a stronger password
  622. hash when it's written to the database in 1.4. This means that if you
  623. upgrade to 1.4 and then need to downgrade to 1.3, version 1.3 won't be able
  624. to read the updated passwords.
  625. * Remedy: Set :setting:`PASSWORD_HASHERS` to use your original password
  626. hashing when you initially upgrade to 1.4. After you confirm your app works
  627. well with Django 1.4 and you won't have to roll back to 1.3, enable the new
  628. password hashes.
  629. django.contrib.flatpages
  630. ~~~~~~~~~~~~~~~~~~~~~~~~
  631. Starting in 1.4, the
  632. :class:`~django.contrib.flatpages.middleware.FlatpageFallbackMiddleware` only
  633. adds a trailing slash and redirects if the resulting URL refers to an existing
  634. flatpage. For example, requesting ``/notaflatpageoravalidurl`` in a previous
  635. version would redirect to ``/notaflatpageoravalidurl/``, which would
  636. subsequently raise a 404. Requesting ``/notaflatpageoravalidurl`` now will
  637. immediately raise a 404.
  638. Also, redirects returned by flatpages are now permanent (with 301 status code),
  639. to match the behavior of :class:`~django.middleware.common.CommonMiddleware`.
  640. Serialization of :class:`~datetime.datetime` and :class:`~datetime.time`
  641. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  642. As a consequence of time-zone support, and according to the ECMA-262
  643. specification, we made changes to the JSON serializer:
  644. * It includes the time zone for aware datetime objects. It raises an exception
  645. for aware time objects.
  646. * It includes milliseconds for datetime and time objects. There is still
  647. some precision loss, because Python stores microseconds (6 digits) and JSON
  648. only supports milliseconds (3 digits). However, it's better than discarding
  649. microseconds entirely.
  650. We changed the XML serializer to use the ISO8601 format for datetimes.
  651. The letter ``T`` is used to separate the date part from the time part, instead
  652. of a space. Time zone information is included in the ``[+-]HH:MM`` format.
  653. Though the serializers now use these new formats when creating fixtures, they
  654. can still load fixtures that use the old format.
  655. ``supports_timezone`` changed to ``False`` for SQLite
  656. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  657. The database feature ``supports_timezone`` used to be ``True`` for SQLite.
  658. Indeed, if you saved an aware datetime object, SQLite stored a string that
  659. included an UTC offset. However, this offset was ignored when loading the value
  660. back from the database, which could corrupt the data.
  661. In the context of time-zone support, this flag was changed to ``False``, and
  662. datetimes are now stored without time-zone information in SQLite. When
  663. :setting:`USE_TZ` is ``False``, if you attempt to save an aware datetime
  664. object, Django raises an exception.
  665. ``MySQLdb``-specific exceptions
  666. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  667. The MySQL backend historically has raised ``MySQLdb.OperationalError``
  668. when a query triggered an exception. We've fixed this bug, and we now raise
  669. :exc:`django.db.DatabaseError` instead. If you were testing for
  670. ``MySQLdb.OperationalError``, you'll need to update your ``except``
  671. clauses.
  672. Database connection's thread-locality
  673. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  674. ``DatabaseWrapper`` objects (i.e. the connection objects referenced by
  675. ``django.db.connection`` and ``django.db.connections["some_alias"]``) used to
  676. be thread-local. They are now global objects in order to be potentially shared
  677. between multiple threads. While the individual connection objects are now
  678. global, the ``django.db.connections`` dictionary referencing those objects is
  679. still thread-local. Therefore if you just use the ORM or
  680. ``DatabaseWrapper.cursor()`` then the behavior is still the same as before.
  681. Note, however, that ``django.db.connection`` does not directly reference the
  682. default ``DatabaseWrapper`` object anymore and is now a proxy to access that
  683. object's attributes. If you need to access the actual ``DatabaseWrapper``
  684. object, use ``django.db.connections[DEFAULT_DB_ALIAS]`` instead.
  685. As part of this change, all underlying SQLite connections are now enabled for
  686. potential thread-sharing (by passing the ``check_same_thread=False`` attribute
  687. to pysqlite). ``DatabaseWrapper`` however preserves the previous behavior by
  688. disabling thread-sharing by default, so this does not affect any existing
  689. code that purely relies on the ORM or on ``DatabaseWrapper.cursor()``.
  690. Finally, while it's now possible to pass connections between threads, Django
  691. doesn't make any effort to synchronize access to the underlying backend.
  692. Concurrency behavior is defined by the underlying backend implementation.
  693. Check their documentation for details.
  694. `COMMENTS_BANNED_USERS_GROUP` setting
  695. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  696. Django's :doc:`comments app </ref/contrib/comments/index>` has historically
  697. supported excluding the comments of a special user group, but we've never
  698. documented the feature properly and didn't enforce the exclusion in other parts
  699. of the app such as the template tags. To fix this problem, we removed the code
  700. from the feed class.
  701. If you rely on the feature and want to restore the old behavior, use a custom
  702. comment model manager to exclude the user group, like this::
  703. from django.conf import settings
  704. from django.contrib.comments.managers import CommentManager
  705. class BanningCommentManager(CommentManager):
  706. def get_query_set(self):
  707. qs = super(BanningCommentManager, self).get_query_set()
  708. if getattr(settings, 'COMMENTS_BANNED_USERS_GROUP', None):
  709. where = ['user_id NOT IN (SELECT user_id FROM auth_user_groups WHERE group_id = %s)']
  710. params = [settings.COMMENTS_BANNED_USERS_GROUP]
  711. qs = qs.extra(where=where, params=params)
  712. return qs
  713. Save this model manager in your custom comment app (e.g., in
  714. ``my_comments_app/managers.py``) and add it your
  715. :ref:`custom comment app model <custom-comment-app-api>`::
  716. from django.db import models
  717. from django.contrib.comments.models import Comment
  718. from my_comments_app.managers import BanningCommentManager
  719. class CommentWithTitle(Comment):
  720. title = models.CharField(max_length=300)
  721. objects = BanningCommentManager()
  722. For more details, see the documentation about
  723. :doc:`customizing the comments framework </ref/contrib/comments/custom>`.
  724. `IGNORABLE_404_STARTS` and `IGNORABLE_404_ENDS` settings
  725. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  726. Until Django 1.3, it was possible to exclude some URLs from Django's
  727. :doc:`404 error reporting</howto/error-reporting>` by adding prefixes to
  728. ``IGNORABLE_404_STARTS`` and suffixes to ``IGNORABLE_404_ENDS``.
  729. In Django 1.4, these two settings are superseded by
  730. :setting:`IGNORABLE_404_URLS`, which is a list of compiled regular
  731. expressions. Django won't send an email for 404 errors on URLs that match any
  732. of them.
  733. Furthermore, the previous settings had some rather arbitrary default values::
  734. IGNORABLE_404_STARTS = ('/cgi-bin/', '/_vti_bin', '/_vti_inf')
  735. IGNORABLE_404_ENDS = ('mail.pl', 'mailform.pl', 'mail.cgi', 'mailform.cgi',
  736. 'favicon.ico', '.php')
  737. It's not Django's role to decide if your website has a legacy ``/cgi-bin/``
  738. section or a ``favicon.ico``. As a consequence, the default values of
  739. :setting:`IGNORABLE_404_URLS`, ``IGNORABLE_404_STARTS``, and
  740. ``IGNORABLE_404_ENDS`` are all now empty.
  741. If you have customized ``IGNORABLE_404_STARTS`` or ``IGNORABLE_404_ENDS``, or
  742. if you want to keep the old default value, you should add the following lines
  743. in your settings file::
  744. import re
  745. IGNORABLE_404_URLS = (
  746. # for each <prefix> in IGNORABLE_404_STARTS
  747. re.compile(r'^<prefix>'),
  748. # for each <suffix> in IGNORABLE_404_ENDS
  749. re.compile(r'<suffix>$'),
  750. )
  751. Don't forget to escape characters that have a special meaning in a regular
  752. expression, such as periods.
  753. CSRF protection extended to PUT and DELETE
  754. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  755. Previously, Django's :doc:`CSRF protection </ref/contrib/csrf/>` provided
  756. protection only against POST requests. Since use of PUT and DELETE methods in
  757. AJAX applications is becoming more common, we now protect all methods not
  758. defined as safe by :rfc:`2616` -- i.e., we exempt GET, HEAD, OPTIONS and TRACE,
  759. and we enforce protection on everything else.
  760. If you're using PUT or DELETE methods in AJAX applications, please see the
  761. :ref:`instructions about using AJAX and CSRF <csrf-ajax>`.
  762. Password reset view now accepts ``subject_template_name``
  763. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  764. The ``password_reset`` view in ``django.contrib.auth`` now accepts a
  765. ``subject_template_name`` parameter, which is passed to the password save form
  766. as a keyword argument. If you are using this view with a custom password reset
  767. form, then you will need to ensure your form's ``save()`` method accepts this
  768. keyword argument.
  769. ``django.core.template_loaders``
  770. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  771. This was an alias to ``django.template.loader`` since 2005, and we've removed it
  772. without emitting a warning due to the length of the deprecation. If your code
  773. still referenced this, please use ``django.template.loader`` instead.
  774. ``django.db.models.fields.URLField.verify_exists``
  775. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  776. This functionality has been removed due to intractable performance and
  777. security issues. Any existing usage of ``verify_exists`` should be
  778. removed.
  779. ``django.core.files.storage.Storage.open``
  780. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  781. The ``open`` method of the base Storage class used to take an obscure parameter
  782. ``mixin`` that allowed you to dynamically change the base classes of the
  783. returned file object. This has been removed. In the rare case you relied on the
  784. ``mixin`` parameter, you can easily achieve the same by overriding the ``open``
  785. method, like this::
  786. from django.core.files import File
  787. from django.core.files.storage import FileSystemStorage
  788. class Spam(File):
  789. """
  790. Spam, spam, spam, spam and spam.
  791. """
  792. def ham(self):
  793. return 'eggs'
  794. class SpamStorage(FileSystemStorage):
  795. """
  796. A custom file storage backend.
  797. """
  798. def open(self, name, mode='rb'):
  799. return Spam(open(self.path(name), mode))
  800. YAML deserializer now uses ``yaml.safe_load``
  801. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  802. ``yaml.load`` is able to construct any Python object, which may trigger
  803. arbitrary code execution if you process a YAML document that comes from an
  804. untrusted source. This feature isn't necessary for Django's YAML deserializer,
  805. whose primary use is to load fixtures consisting of simple objects. Even though
  806. fixtures are trusted data, the YAML deserializer now uses ``yaml.safe_load``
  807. for additional security.
  808. Session cookies now have the ``httponly`` flag by default
  809. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  810. Session cookies now include the ``httponly`` attribute by default to
  811. help reduce the impact of potential XSS attacks. As a consequence of
  812. this change, session cookie data, including sessionid, is no longer
  813. accessible from JavaScript in many browsers. For strict backwards
  814. compatibility, use ``SESSION_COOKIE_HTTPONLY = False`` in your
  815. settings file.
  816. The :tfilter:`urlize` filter no longer escapes every URL
  817. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  818. When a URL contains a ``%xx`` sequence, where ``xx`` are two hexadecimal
  819. digits, :tfilter:`urlize` now assumes that the URL is already escaped and
  820. doesn't apply URL escaping again. This is wrong for URLs whose unquoted form
  821. contains a ``%xx`` sequence, but such URLs are very unlikely to happen in the
  822. wild, because they would confuse browsers too.
  823. ``assertTemplateUsed`` and ``assertTemplateNotUsed`` as context manager
  824. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  825. It's now possible to check whether a template was used within a block of
  826. code with :meth:`~django.test.TestCase.assertTemplateUsed` and
  827. :meth:`~django.test.TestCase.assertTemplateNotUsed`. And they
  828. can be used as a context manager::
  829. with self.assertTemplateUsed('index.html'):
  830. render_to_string('index.html')
  831. with self.assertTemplateNotUsed('base.html'):
  832. render_to_string('index.html')
  833. See the :ref:`assertion documentation<assertions>` for more.
  834. Database connections after running the test suite
  835. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  836. The default test runner no longer restores the database connections after
  837. tests' execution. This prevents the production database from being exposed to
  838. potential threads that would still be running and attempting to create new
  839. connections.
  840. If your code relied on connections to the production database being created
  841. after tests' execution, then you can restore the previous behavior by
  842. subclassing ``DjangoTestRunner`` and overriding its ``teardown_databases()``
  843. method.
  844. Output of :djadmin:`manage.py help <help>`
  845. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  846. :djadmin:`manage.py help <help>` now groups available commands by application.
  847. If you depended on the output of this command -- if you parsed it, for example
  848. -- then you'll need to update your code. To get a list of all available
  849. management commands in a script, use
  850. :djadmin:`manage.py help --commands <help>` instead.
  851. ``extends`` template tag
  852. ~~~~~~~~~~~~~~~~~~~~~~~~
  853. Previously, the :ttag:`extends` tag used a buggy method of parsing arguments,
  854. which could lead to it erroneously considering an argument as a string literal
  855. when it wasn't. It now uses ``parser.compile_filter``, like other tags.
  856. The internals of the tag aren't part of the official stable API, but in the
  857. interests of full disclosure, the ``ExtendsNode.__init__`` definition has
  858. changed, which may break any custom tags that use this class.
  859. Loading some incomplete fixtures no longer works
  860. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  861. Prior to 1.4, a default value was inserted for fixture objects that were missing
  862. a specific date or datetime value when auto_now or auto_now_add was set for the
  863. field. This was something that should not have worked, and in 1.4 loading such
  864. incomplete fixtures will fail. Because fixtures are a raw import, they should
  865. explicitly specify all field values, regardless of field options on the model.
  866. Development Server Multithreading
  867. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  868. The development server is now is multithreaded by default. Use the
  869. :djadminopt:`--nothreading` option to disable the use of threading in the
  870. development server::
  871. django-admin.py runserver --nothreading
  872. Attributes disabled in markdown when safe mode set
  873. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  874. Prior to Django 1.4, attributes were included in any markdown output regardless
  875. of safe mode setting of the filter. With version > 2.1 of the Python-Markdown
  876. library, an enable_attributes option was added. When the safe argument is
  877. passed to the markdown filter, both the ``safe_mode=True`` and
  878. ``enable_attributes=False`` options are set. If using a version of the
  879. Python-Markdown library less than 2.1, a warning is issued that the output is
  880. insecure.
  881. FormMixin get_initial returns an instance-specific dictionary
  882. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  883. In Django 1.3, the ``get_initial`` method of the
  884. :class:`django.views.generic.edit.FormMixin` class was returning the
  885. class ``initial`` dictionary. This has been fixed to return a copy of this
  886. dictionary, so form instances can modify their initial data without messing
  887. with the class variable.
  888. Features deprecated in 1.4
  889. ==========================
  890. Old styles of calling ``cache_page`` decorator
  891. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  892. Some legacy ways of calling :func:`~django.views.decorators.cache.cache_page`
  893. have been deprecated. Please see the documentation for the correct way to use
  894. this decorator.
  895. Support for PostgreSQL versions older than 8.2
  896. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  897. Django 1.3 dropped support for PostgreSQL versions older than 8.0, and we
  898. suggested using a more recent version because of performance improvements
  899. and, more importantly, the end of upstream support periods for 8.0 and 8.1
  900. was near (November 2010).
  901. Django 1.4 takes that policy further and sets 8.2 as the minimum PostgreSQL
  902. version it officially supports.
  903. Request exceptions are now always logged
  904. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  905. When we added :doc:`logging support </topics/logging/>` in Django in 1.3, the
  906. admin error email support was moved into the
  907. :class:`django.utils.log.AdminEmailHandler`, attached to the
  908. ``'django.request'`` logger. In order to maintain the established behavior of
  909. error emails, the ``'django.request'`` logger was called only when
  910. :setting:`DEBUG` was ``False``.
  911. To increase the flexibility of error logging for requests, the
  912. ``'django.request'`` logger is now called regardless of the value of
  913. :setting:`DEBUG`, and the default settings file for new projects now includes a
  914. separate filter attached to :class:`django.utils.log.AdminEmailHandler` to
  915. prevent admin error emails in ``DEBUG`` mode::
  916. 'filters': {
  917. 'require_debug_false': {
  918. '()': 'django.utils.log.RequireDebugFalse'
  919. }
  920. },
  921. 'handlers': {
  922. 'mail_admins': {
  923. 'level': 'ERROR',
  924. 'filters': ['require_debug_false'],
  925. 'class': 'django.utils.log.AdminEmailHandler'
  926. }
  927. },
  928. If your project was created prior to this change, your :setting:`LOGGING`
  929. setting will not include this new filter. In order to maintain
  930. backwards-compatibility, Django will detect that your ``'mail_admins'`` handler
  931. configuration includes no ``'filters'`` section and will automatically add
  932. this filter for you and issue a pending-deprecation warning. This will become a
  933. deprecation warning in Django 1.5, and in Django 1.6 the
  934. backwards-compatibility shim will be removed entirely.
  935. The existence of any ``'filters'`` key under the ``'mail_admins'`` handler will
  936. disable this backward-compatibility shim and deprecation warning.
  937. ``django.conf.urls.defaults``
  938. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  939. Until Django 1.3, the functions :func:`~django.conf.urls.include`,
  940. :func:`~django.conf.urls.patterns` and :func:`~django.conf.urls.url` plus
  941. :data:`~django.conf.urls.handler404`, :data:`~django.conf.urls.handler500`
  942. were located in a ``django.conf.urls.defaults`` module.
  943. In Django 1.4, they live in :mod:`django.conf.urls`.
  944. ``django.contrib.databrowse``
  945. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  946. Databrowse has not seen active development for some time, and this does not show
  947. any sign of changing. There had been a suggestion for a `GSOC project`_ to
  948. integrate the functionality of databrowse into the admin, but no progress was
  949. made. While Databrowse has been deprecated, an enhancement of
  950. ``django.contrib.admin`` providing a similar feature set is still possible.
  951. .. _GSOC project: https://code.djangoproject.com/wiki/SummerOfCode2011#Integratedatabrowseintotheadmin
  952. The code that powers Databrowse is licensed under the same terms as Django
  953. itself, so it's available to be adopted by an individual or group as
  954. a third-party project.
  955. ``django.core.management.setup_environ``
  956. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  957. This function temporarily modified ``sys.path`` in order to make the parent
  958. "project" directory importable under the old flat :djadmin:`startproject`
  959. layout. This function is now deprecated, as its path workarounds are no longer
  960. needed with the new ``manage.py`` and default project layout.
  961. This function was never documented or part of the public API, but it was widely
  962. recommended for use in setting up a "Django environment" for a user script.
  963. These uses should be replaced by setting the ``DJANGO_SETTINGS_MODULE``
  964. environment variable or using :func:`django.conf.settings.configure`.
  965. ``django.core.management.execute_manager``
  966. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  967. This function was previously used by ``manage.py`` to execute a management
  968. command. It is identical to
  969. ``django.core.management.execute_from_command_line``, except that it first
  970. calls ``setup_environ``, which is now deprecated. As such, ``execute_manager``
  971. is also deprecated; ``execute_from_command_line`` can be used instead. Neither
  972. of these functions is documented as part of the public API, but a deprecation
  973. path is needed due to use in existing ``manage.py`` files.
  974. ``is_safe`` and ``needs_autoescape`` attributes of template filters
  975. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  976. Two flags, ``is_safe`` and ``needs_autoescape``, define how each template filter
  977. interacts with Django's auto-escaping behavior. They used to be attributes of
  978. the filter function::
  979. @register.filter
  980. def noop(value):
  981. return value
  982. noop.is_safe = True
  983. However, this technique caused some problems in combination with decorators,
  984. especially :func:`@stringfilter <django.template.defaultfilters.stringfilter>`.
  985. Now, the flags are keyword arguments of :meth:`@register.filter
  986. <django.template.Library.filter>`::
  987. @register.filter(is_safe=True)
  988. def noop(value):
  989. return value
  990. See :ref:`filters and auto-escaping <filters-auto-escaping>` for more information.
  991. Wildcard expansion of application names in `INSTALLED_APPS`
  992. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  993. Until Django 1.3, :setting:`INSTALLED_APPS` accepted wildcards in application
  994. names, like ``django.contrib.*``. The expansion was performed by a
  995. filesystem-based implementation of ``from <package> import *``. Unfortunately,
  996. `this can't be done reliably`_.
  997. This behavior was never documented. Since it is un-pythonic and not obviously
  998. useful, it was removed in Django 1.4. If you relied on it, you must edit your
  999. settings file to list all your applications explicitly.
  1000. .. _this can't be done reliably: http://docs.python.org/tutorial/modules.html#importing-from-a-package
  1001. ``HttpRequest.raw_post_data`` renamed to ``HttpRequest.body``
  1002. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1003. This attribute was confusingly named ``HttpRequest.raw_post_data``, but it
  1004. actually provided the body of the HTTP request. It's been renamed to
  1005. ``HttpRequest.body``, and ``HttpRequest.raw_post_data`` has been deprecated.
  1006. ``django.contrib.sitemaps`` bug fix with potential performance implications
  1007. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1008. In previous versions, ``Paginator`` objects used in sitemap classes were
  1009. cached, which could result in stale site maps. We've removed the caching, so
  1010. each request to a site map now creates a new Paginator object and calls the
  1011. :attr:`~django.contrib.sitemaps.Sitemap.items()` method of the
  1012. :class:`~django.contrib.sitemaps.Sitemap` subclass. Depending on what your
  1013. ``items()`` method is doing, this may have a negative performance impact.
  1014. To mitigate the performance impact, consider using the :doc:`caching
  1015. framework </topics/cache>` within your ``Sitemap`` subclass.
  1016. Versions of Python-Markdown earlier than 2.1
  1017. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1018. Versions of Python-Markdown earlier than 2.1 do not support the option to
  1019. disable attributes. As a security issue, earlier versions of this library will
  1020. not be supported by the markup contrib app in 1.5 under an accelerated
  1021. deprecation timeline.