1.4.txt 56 KB

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