1.4.txt 56 KB

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