2
0

1.7.txt 81 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855
  1. ========================
  2. Django 1.7 release notes
  3. ========================
  4. *September 2, 2014*
  5. Welcome to Django 1.7!
  6. These release notes cover the `new features`_, as well as some `backwards
  7. incompatible changes`_ you'll want to be aware of when upgrading from Django
  8. 1.6 or older versions. We've `begun the deprecation process for some features`_,
  9. and some features have reached the end of their deprecation process and
  10. `have been removed`_.
  11. .. _`new features`: `What's new in Django 1.7`_
  12. .. _`backwards incompatible changes`: `Backwards incompatible changes in 1.7`_
  13. .. _`begun the deprecation process for some features`: `Features deprecated in 1.7`_
  14. .. _`have been removed`: `Features removed in 1.7`_
  15. Python compatibility
  16. ====================
  17. Django 1.7 requires Python 2.7 or above, though we **highly recommend**
  18. the latest minor release. Support for Python 2.6 has been dropped and support
  19. for Python 3.4 has been added.
  20. This change should affect only a small number of Django users, as most
  21. operating-system vendors today are shipping Python 2.7 or newer as their default
  22. version. If you're still using Python 2.6, however, you'll need to stick to
  23. Django 1.6 until you can upgrade your Python version. Per :doc:`our support
  24. policy </internals/release-process>`, Django 1.6 will continue to receive
  25. security support until the release of Django 1.8.
  26. What's new in Django 1.7
  27. ========================
  28. Schema migrations
  29. ~~~~~~~~~~~~~~~~~
  30. Django now has built-in support for schema migrations. It allows models
  31. to be updated, changed, and deleted by creating migration files that represent
  32. the model changes and which can be run on any development, staging or production
  33. database.
  34. Migrations are covered in :doc:`their own documentation</topics/migrations>`,
  35. but a few of the key features are:
  36. * ``syncdb`` has been deprecated and replaced by ``migrate``. Don't worry -
  37. calls to ``syncdb`` will still work as before.
  38. * A new ``makemigrations`` command provides an easy way to autodetect changes
  39. to your models and make migrations for them.
  40. ``django.db.models.signals.pre_syncdb`` and
  41. ``django.db.models.signals.post_syncdb`` have been deprecated,
  42. to be replaced by :data:`~django.db.models.signals.pre_migrate` and
  43. :data:`~django.db.models.signals.post_migrate` respectively. These
  44. new signals have slightly different arguments. Check the
  45. documentation for details.
  46. * The ``allow_syncdb`` method on database routers is now called ``allow_migrate``,
  47. but still performs the same function. Routers with ``allow_syncdb`` methods
  48. will still work, but that method name is deprecated and you should change
  49. it as soon as possible (nothing more than renaming is required).
  50. * ``initial_data`` fixtures are no longer loaded for apps with migrations; if
  51. you want to load initial data for an app, we suggest you create a migration for
  52. your application and define a :class:`~django.db.migrations.operations.RunPython`
  53. or :class:`~django.db.migrations.operations.RunSQL` operation in the ``operations`` section of the migration.
  54. * Test rollback behavior is different for apps with migrations; in particular,
  55. Django will no longer emulate rollbacks on non-transactional databases or
  56. inside ``TransactionTestCase`` :ref:`unless specifically requested
  57. <test-case-serialized-rollback>`.
  58. * It is not advised to have apps without migrations depend on (have a
  59. :ref:`ForeignKey <ref-foreignkey>` or :ref:`ManyToManyField <ref-manytomany>`
  60. to) apps with migrations.
  61. * If you are upgrading from South, see our :ref:`upgrading-from-south`
  62. documentation, and third-party app authors should read the
  63. `South 1.0 release notes <http://south.readthedocs.org/en/latest/releasenotes/1.0.html#library-migration-path>`_
  64. for details on how to support South and Django migrations simultaneously.
  65. .. _app-loading-refactor-17-release-note:
  66. App-loading refactor
  67. ~~~~~~~~~~~~~~~~~~~~
  68. Historically, Django applications were tightly linked to models. A singleton
  69. known as the "app cache" dealt with both installed applications and models.
  70. The models module was used as an identifier for applications in many APIs.
  71. As the concept of :doc:`Django applications </ref/applications>` matured, this
  72. code showed some shortcomings. It has been refactored into an "app registry"
  73. where models modules no longer have a central role and where it's possible to
  74. attach configuration data to applications.
  75. Improvements thus far include:
  76. * Applications can run code at startup, before Django does anything else, with
  77. the :meth:`~django.apps.AppConfig.ready` method of their configuration.
  78. * Application labels are assigned correctly to models even when they're
  79. defined outside of ``models.py``. You don't have to set
  80. :attr:`~django.db.models.Options.app_label` explicitly any more.
  81. * It is possible to omit ``models.py`` entirely if an application doesn't
  82. have any models.
  83. * Applications can be relabeled with the :attr:`~django.apps.AppConfig.label`
  84. attribute of application configurations, to work around label conflicts.
  85. * The name of applications can be customized in the admin with the
  86. :attr:`~django.apps.AppConfig.verbose_name` of application configurations.
  87. * The admin automatically calls :func:`~django.contrib.admin.autodiscover()`
  88. when Django starts. You can consequently remove this line from your
  89. URLconf.
  90. * Django imports all application configurations and models as soon as it
  91. starts, through a deterministic and straightforward process. This should
  92. make it easier to diagnose import issues such as import loops.
  93. New method on Field subclasses
  94. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  95. To help power both schema migrations and to enable easier addition of
  96. composite keys in future releases of Django, the
  97. :class:`~django.db.models.Field` API now has a new required method:
  98. ``deconstruct()``.
  99. This method takes no arguments, and returns a tuple of four items:
  100. * ``name``: The field's attribute name on its parent model, or None if it is not part of a model
  101. * ``path``: A dotted, Python path to the class of this field, including the class name.
  102. * ``args``: Positional arguments, as a list
  103. * ``kwargs``: Keyword arguments, as a dict
  104. These four values allow any field to be serialized into a file, as well as
  105. allowing the field to be copied safely, both essential parts of these new features.
  106. This change should not affect you unless you write custom Field subclasses;
  107. if you do, you may need to reimplement the ``deconstruct()`` method if your
  108. subclass changes the method signature of ``__init__`` in any way. If your
  109. field just inherits from a built-in Django field and doesn't override ``__init__``,
  110. no changes are necessary.
  111. If you do need to override ``deconstruct()``, a good place to start is the
  112. built-in Django fields (``django/db/models/fields/__init__.py``) as several
  113. fields, including ``DecimalField`` and ``DateField``, override it and show how
  114. to call the method on the superclass and simply add or remove extra arguments.
  115. This also means that all arguments to fields must themselves be serializable;
  116. to see what we consider serializable, and to find out how to make your own
  117. classes serializable, read the
  118. :ref:`migration serialization documentation <migration-serializing>`.
  119. Calling custom ``QuerySet`` methods from the ``Manager``
  120. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  121. Historically, the recommended way to make reusable model queries was to create
  122. methods on a custom ``Manager`` class. The problem with this approach was that
  123. after the first method call, you'd get back a ``QuerySet`` instance and
  124. couldn't call additional custom manager methods.
  125. Though not documented, it was common to work around this issue by creating a
  126. custom ``QuerySet`` so that custom methods could be chained; but the solution
  127. had a number of drawbacks:
  128. * The custom ``QuerySet`` and its custom methods were lost after the first
  129. call to ``values()`` or ``values_list()``.
  130. * Writing a custom ``Manager`` was still necessary to return the custom
  131. ``QuerySet`` class and all methods that were desired on the ``Manager``
  132. had to be proxied to the ``QuerySet``. The whole process went against
  133. the DRY principle.
  134. The :meth:`QuerySet.as_manager() <django.db.models.query.QuerySet.as_manager>`
  135. class method can now directly :ref:`create Manager with QuerySet methods
  136. <create-manager-with-queryset-methods>`::
  137. class FoodQuerySet(models.QuerySet):
  138. def pizzas(self):
  139. return self.filter(kind='pizza')
  140. def vegetarian(self):
  141. return self.filter(vegetarian=True)
  142. class Food(models.Model):
  143. kind = models.CharField(max_length=50)
  144. vegetarian = models.BooleanField(default=False)
  145. objects = FoodQuerySet.as_manager()
  146. Food.objects.pizzas().vegetarian()
  147. Using a custom manager when traversing reverse relations
  148. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  149. It is now possible to :ref:`specify a custom manager
  150. <using-custom-reverse-manager>` when traversing a reverse relationship::
  151. class Blog(models.Model):
  152. pass
  153. class Entry(models.Model):
  154. blog = models.ForeignKey(Blog)
  155. objects = models.Manager() # Default Manager
  156. entries = EntryManager() # Custom Manager
  157. b = Blog.objects.get(id=1)
  158. b.entry_set(manager='entries').all()
  159. New system check framework
  160. ~~~~~~~~~~~~~~~~~~~~~~~~~~
  161. We've added a new :doc:`System check framework </ref/checks>` for
  162. detecting common problems (like invalid models) and providing hints for
  163. resolving those problems. The framework is extensible so you can add your
  164. own checks for your own apps and libraries.
  165. To perform system checks, you use the :djadmin:`check` management command.
  166. This command replaces the older ``validate`` management command.
  167. New ``Prefetch`` object for advanced ``prefetch_related`` operations.
  168. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  169. The new :class:`~django.db.models.Prefetch` object allows customizing
  170. prefetch operations.
  171. You can specify the ``QuerySet`` used to traverse a given relation
  172. or customize the storage location of prefetch results.
  173. This enables things like filtering prefetched relations, calling
  174. :meth:`~django.db.models.query.QuerySet.select_related()` from a prefetched
  175. relation, or prefetching the same relation multiple times with different
  176. querysets. See :meth:`~django.db.models.query.QuerySet.prefetch_related()`
  177. for more details.
  178. Admin shortcuts support time zones
  179. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  180. The "today" and "now" shortcuts next to date and time input widgets in the
  181. admin are now operating in the :ref:`current time zone
  182. <default-current-time-zone>`. Previously, they used the browser time zone,
  183. which could result in saving the wrong value when it didn't match the current
  184. time zone on the server.
  185. In addition, the widgets now display a help message when the browser and
  186. server time zone are different, to clarify how the value inserted in the field
  187. will be interpreted.
  188. Using database cursors as context managers
  189. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  190. Prior to Python 2.7, database cursors could be used as a context manager. The
  191. specific backend's cursor defined the behavior of the context manager. The
  192. behavior of magic method lookups was changed with Python 2.7 and cursors were
  193. no longer usable as context managers.
  194. Django 1.7 allows a cursor to be used as a context manager. That is,
  195. the following can be used::
  196. with connection.cursor() as c:
  197. c.execute(...)
  198. instead of::
  199. c = connection.cursor()
  200. try:
  201. c.execute(...)
  202. finally:
  203. c.close()
  204. Custom lookups
  205. ~~~~~~~~~~~~~~
  206. It is now possible to write custom lookups and transforms for the ORM.
  207. Custom lookups work just like Django's inbuilt lookups (e.g. ``lte``,
  208. ``icontains``) while transforms are a new concept.
  209. The :class:`django.db.models.Lookup` class provides a way to add lookup
  210. operators for model fields. As an example it is possible to add ``day_lte``
  211. operator for ``DateFields``.
  212. The :class:`django.db.models.Transform` class allows transformations of
  213. database values prior to the final lookup. For example it is possible to
  214. write a ``year`` transform that extracts year from the field's value.
  215. Transforms allow for chaining. After the ``year`` transform has been added
  216. to ``DateField`` it is possible to filter on the transformed value, for
  217. example ``qs.filter(author__birthdate__year__lte=1981)``.
  218. For more information about both custom lookups and transforms refer to
  219. the :doc:`custom lookups </howto/custom-lookups>` documentation.
  220. Improvements to ``Form`` error handling
  221. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  222. ``Form.add_error()``
  223. ^^^^^^^^^^^^^^^^^^^^
  224. Previously there were two main patterns for handling errors in forms:
  225. * Raising a :exc:`~django.core.exceptions.ValidationError` from within certain
  226. functions (e.g. ``Field.clean()``, ``Form.clean_<fieldname>()``, or
  227. ``Form.clean()`` for non-field errors.)
  228. * Fiddling with ``Form._errors`` when targeting a specific field in
  229. ``Form.clean()`` or adding errors from outside of a "clean" method
  230. (e.g. directly from a view).
  231. Using the former pattern was straightforward since the form can guess from the
  232. context (i.e. which method raised the exception) where the errors belong and
  233. automatically process them. This remains the canonical way of adding errors
  234. when possible. However the latter was fiddly and error-prone, since the burden
  235. of handling edge cases fell on the user.
  236. The new :meth:`~django.forms.Form.add_error()` method allows adding errors
  237. to specific form fields from anywhere without having to worry about the details
  238. such as creating instances of ``django.forms.utils.ErrorList`` or dealing with
  239. ``Form.cleaned_data``. This new API replaces manipulating ``Form._errors``
  240. which now becomes a private API.
  241. See :ref:`validating-fields-with-clean` for an example using
  242. ``Form.add_error()``.
  243. Error metadata
  244. ^^^^^^^^^^^^^^
  245. The :exc:`~django.core.exceptions.ValidationError` constructor accepts metadata
  246. such as error ``code`` or ``params`` which are then available for interpolating
  247. into the error message (see :ref:`raising-validation-error` for more details);
  248. however, before Django 1.7 those metadata were discarded as soon as the errors
  249. were added to :attr:`Form.errors <django.forms.Form.errors>`.
  250. :attr:`Form.errors <django.forms.Form.errors>` and
  251. ``django.forms.utils.ErrorList`` now store the ``ValidationError`` instances
  252. so these metadata can be retrieved at any time through the new
  253. :meth:`Form.errors.as_data <django.forms.Form.errors.as_data()>` method.
  254. The retrieved ``ValidationError`` instances can then be identified thanks to
  255. their error ``code`` which enables things like rewriting the error's message
  256. or writing custom logic in a view when a given error is present. It can also
  257. be used to serialize the errors in a custom format such as XML.
  258. The new :meth:`Form.errors.as_json() <django.forms.Form.errors.as_json()>`
  259. method is a convenience method which returns error messages along with error
  260. codes serialized as JSON. ``as_json()`` uses ``as_data()`` and gives an idea
  261. of how the new system could be extended.
  262. Error containers and backward compatibility
  263. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  264. Heavy changes to the various error containers were necessary in order
  265. to support the features above, specifically
  266. :attr:`Form.errors <django.forms.Form.errors>`,
  267. ``django.forms.utils.ErrorList``, and the internal storages of
  268. :exc:`~django.core.exceptions.ValidationError`. These containers which used
  269. to store error strings now store ``ValidationError`` instances and public APIs
  270. have been adapted to make this as transparent as possible, but if you've been
  271. using private APIs, some of the changes are backwards incompatible; see
  272. :ref:`validation-error-constructor-and-internal-storage` for more details.
  273. Minor features
  274. ~~~~~~~~~~~~~~
  275. :mod:`django.contrib.admin`
  276. ^^^^^^^^^^^^^^^^^^^^^^^^^^^
  277. * You can now implement :attr:`~django.contrib.admin.AdminSite.site_header`,
  278. :attr:`~django.contrib.admin.AdminSite.site_title`, and
  279. :attr:`~django.contrib.admin.AdminSite.index_title` attributes on a custom
  280. :class:`~django.contrib.admin.AdminSite` in order to easily change the admin
  281. site's page title and header text. No more needing to override templates!
  282. * Buttons in :mod:`django.contrib.admin` now use the ``border-radius`` CSS
  283. property for rounded corners rather than GIF background images.
  284. * Some admin templates now have ``app-<app_name>`` and ``model-<model_name>``
  285. classes in their ``<body>`` tag to allow customizing the CSS per app or per
  286. model.
  287. * The admin changelist cells now have a ``field-<field_name>`` class in the
  288. HTML to enable style customizations.
  289. * The admin's search fields can now be customized per-request thanks to the new
  290. :meth:`django.contrib.admin.ModelAdmin.get_search_fields` method.
  291. * The :meth:`ModelAdmin.get_fields()
  292. <django.contrib.admin.ModelAdmin.get_fields>` method may be overridden to
  293. customize the value of :attr:`ModelAdmin.fields
  294. <django.contrib.admin.ModelAdmin.fields>`.
  295. * In addition to the existing ``admin.site.register`` syntax, you can use the
  296. new :func:`~django.contrib.admin.register` decorator to register a
  297. :class:`~django.contrib.admin.ModelAdmin`.
  298. * You may specify :meth:`ModelAdmin.list_display_links
  299. <django.contrib.admin.ModelAdmin.list_display_links>` ``= None`` to disable
  300. links on the change list page grid.
  301. * You may now specify :attr:`ModelAdmin.view_on_site
  302. <django.contrib.admin.ModelAdmin.view_on_site>` to control whether or not to
  303. display the "View on site" link.
  304. * You can specify a descending ordering for a :attr:`ModelAdmin.list_display
  305. <django.contrib.admin.ModelAdmin.list_display>` value by prefixing the
  306. ``admin_order_field`` value with a hyphen.
  307. * The :meth:`ModelAdmin.get_changeform_initial_data()
  308. <django.contrib.admin.ModelAdmin.get_changeform_initial_data>` method may be
  309. overridden to define custom behavior for setting initial change form data.
  310. :mod:`django.contrib.auth`
  311. ^^^^^^^^^^^^^^^^^^^^^^^^^^
  312. * Any ``**kwargs`` passed to
  313. :meth:`~django.contrib.auth.models.User.email_user()` are passed to the
  314. underlying :meth:`~django.core.mail.send_mail()` call.
  315. * The :func:`~django.contrib.auth.decorators.permission_required` decorator can
  316. take a list of permissions as well as a single permission.
  317. * You can override the new :meth:`AuthenticationForm.confirm_login_allowed()
  318. <django.contrib.auth.forms.AuthenticationForm.confirm_login_allowed>` method
  319. to more easily customize the login policy.
  320. * :func:`django.contrib.auth.views.password_reset` takes an optional
  321. ``html_email_template_name`` parameter used to send a multipart HTML email
  322. for password resets.
  323. * The :meth:`AbstractBaseUser.get_session_auth_hash()
  324. <django.contrib.auth.models.AbstractBaseUser.get_session_auth_hash>`
  325. method was added and if your :setting:`AUTH_USER_MODEL` inherits from
  326. :class:`~django.contrib.auth.models.AbstractBaseUser`, changing a user's
  327. password now invalidates old sessions if the
  328. ``django.contrib.auth.middleware.SessionAuthenticationMiddleware`` is
  329. enabled. See :ref:`session-invalidation-on-password-change` for more details.
  330. ``django.contrib.formtools``
  331. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  332. * Calls to :meth:`WizardView.done()
  333. <formtools.wizard.views.WizardView.done>` now include a
  334. ``form_dict`` to allow easier access to forms by their step name.
  335. :mod:`django.contrib.gis`
  336. ^^^^^^^^^^^^^^^^^^^^^^^^^^
  337. * The default OpenLayers library version included in widgets has been updated
  338. from 2.11 to 2.13.
  339. * Prepared geometries now also support the ``crosses``, ``disjoint``,
  340. ``overlaps``, ``touches`` and ``within`` predicates, if GEOS 3.3 or later is
  341. installed.
  342. :mod:`django.contrib.messages`
  343. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  344. * The backends for :mod:`django.contrib.messages` that use cookies, will now
  345. follow the :setting:`SESSION_COOKIE_SECURE` and
  346. :setting:`SESSION_COOKIE_HTTPONLY` settings.
  347. * The :ref:`messages context processor <message-displaying>` now adds a
  348. dictionary of default levels under the name ``DEFAULT_MESSAGE_LEVELS``.
  349. * :class:`~django.contrib.messages.storage.base.Message` objects now have a
  350. ``level_tag`` attribute that contains the string representation of the
  351. message level.
  352. :mod:`django.contrib.redirects`
  353. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  354. * :class:`~django.contrib.redirects.middleware.RedirectFallbackMiddleware`
  355. has two new attributes
  356. (:attr:`~django.contrib.redirects.middleware.RedirectFallbackMiddleware.response_gone_class`
  357. and
  358. :attr:`~django.contrib.redirects.middleware.RedirectFallbackMiddleware.response_redirect_class`)
  359. that specify the types of :class:`~django.http.HttpResponse` instances the
  360. middleware returns.
  361. :mod:`django.contrib.sessions`
  362. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  363. * The ``"django.contrib.sessions.backends.cached_db"`` session backend now
  364. respects :setting:`SESSION_CACHE_ALIAS`. In previous versions, it always used
  365. the `default` cache.
  366. :mod:`django.contrib.sitemaps`
  367. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  368. * The :mod:`sitemap framework<django.contrib.sitemaps>` now makes use of
  369. :attr:`~django.contrib.sitemaps.Sitemap.lastmod` to set a ``Last-Modified``
  370. header in the response. This makes it possible for the
  371. :class:`~django.middleware.http.ConditionalGetMiddleware` to handle
  372. conditional ``GET`` requests for sitemaps which set ``lastmod``.
  373. :mod:`django.contrib.sites`
  374. ^^^^^^^^^^^^^^^^^^^^^^^^^^^
  375. * The new :class:`django.contrib.sites.middleware.CurrentSiteMiddleware` allows
  376. setting the current site on each request.
  377. :mod:`django.contrib.staticfiles`
  378. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  379. * The :ref:`static files storage classes <staticfiles-storages>` may be
  380. subclassed to override the permissions that collected static files and
  381. directories receive by setting the
  382. :attr:`~django.core.files.storage.FileSystemStorage.file_permissions_mode`
  383. and :attr:`~django.core.files.storage.FileSystemStorage.directory_permissions_mode`
  384. parameters. See :djadmin:`collectstatic` for example usage.
  385. * The :class:`~django.contrib.staticfiles.storage.CachedStaticFilesStorage`
  386. backend gets a sibling class called
  387. :class:`~django.contrib.staticfiles.storage.ManifestStaticFilesStorage`
  388. that doesn't use the cache system at all but instead a JSON file called
  389. ``staticfiles.json`` for storing the mapping between the original file name
  390. (e.g. ``css/styles.css``) and the hashed file name (e.g.
  391. ``css/styles.55e7cbb9ba48.css``). The ``staticfiles.json`` file is created
  392. when running the :djadmin:`collectstatic` management command and should
  393. be a less expensive alternative for remote storages such as Amazon S3.
  394. See the :class:`~django.contrib.staticfiles.storage.ManifestStaticFilesStorage`
  395. docs for more information.
  396. * :djadmin:`findstatic` now accepts verbosity flag level 2, meaning it will
  397. show the relative paths of the directories it searched. See
  398. :djadmin:`findstatic` for example output.
  399. :mod:`django.contrib.syndication`
  400. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  401. * The :class:`~django.utils.feedgenerator.Atom1Feed` syndication feed's
  402. ``updated`` element now utilizes ``updateddate`` instead of ``pubdate``,
  403. allowing the ``published`` element to be included in the feed (which
  404. relies on ``pubdate``).
  405. Cache
  406. ^^^^^
  407. * Access to caches configured in :setting:`CACHES` is now available via
  408. :data:`django.core.cache.caches`. This dict-like object provides a different
  409. instance per thread. It supersedes ``django.core.cache.get_cache()`` which
  410. is now deprecated.
  411. * If you instantiate cache backends directly, be aware that they aren't
  412. thread-safe any more, as :data:`django.core.cache.caches` now yields
  413. different instances per thread.
  414. * Defining the :setting:`TIMEOUT <CACHES-TIMEOUT>` argument of the
  415. :setting:`CACHES` setting as ``None`` will set the cache keys as
  416. "non-expiring" by default. Previously, it was only possible to pass
  417. ``timeout=None`` to the cache backend's ``set()`` method.
  418. Cross Site Request Forgery
  419. ^^^^^^^^^^^^^^^^^^^^^^^^^^
  420. * The :setting:`CSRF_COOKIE_AGE` setting facilitates the use of session-based
  421. CSRF cookies.
  422. Email
  423. ^^^^^
  424. * :func:`~django.core.mail.send_mail` now accepts an ``html_message``
  425. parameter for sending a multipart ``text/plain`` and ``text/html`` email.
  426. * The SMTP :class:`~django.core.mail.backends.smtp.EmailBackend` now accepts a
  427. ``timeout`` parameter.
  428. File Storage
  429. ^^^^^^^^^^^^
  430. * File locking on Windows previously depended on the PyWin32 package; if it
  431. wasn't installed, file locking failed silently. That dependency has been
  432. removed, and file locking is now implemented natively on both Windows
  433. and Unix.
  434. File Uploads
  435. ^^^^^^^^^^^^
  436. * The new :attr:`UploadedFile.content_type_extra
  437. <django.core.files.uploadedfile.UploadedFile.content_type_extra>` attribute
  438. contains extra parameters passed to the ``content-type`` header on a file
  439. upload.
  440. * The new :setting:`FILE_UPLOAD_DIRECTORY_PERMISSIONS` setting controls
  441. the file system permissions of directories created during file upload, like
  442. :setting:`FILE_UPLOAD_PERMISSIONS` does for the files themselves.
  443. * The :attr:`FileField.upload_to <django.db.models.FileField.upload_to>`
  444. attribute is now optional. If it is omitted or given ``None`` or an empty
  445. string, a subdirectory won't be used for storing the uploaded files.
  446. * Uploaded files are now explicitly closed before the response is delivered to
  447. the client. Partially uploaded files are also closed as long as they are
  448. named ``file`` in the upload handler.
  449. * :meth:`Storage.get_available_name()
  450. <django.core.files.storage.Storage.get_available_name>` now appends an
  451. underscore plus a random 7 character alphanumeric string (e.g.
  452. ``"_x3a1gho"``), rather than iterating through an underscore followed by a
  453. number (e.g. ``"_1"``, ``"_2"``, etc.) to prevent a denial-of-service attack.
  454. This change was also made in the 1.6.6, 1.5.9, and 1.4.14 security releases.
  455. Forms
  456. ^^^^^
  457. * The ``<label>`` and ``<input>`` tags rendered by
  458. :class:`~django.forms.RadioSelect` and
  459. :class:`~django.forms.CheckboxSelectMultiple` when looping over the radio
  460. buttons or checkboxes now include ``for`` and ``id`` attributes, respectively.
  461. Each radio button or checkbox includes an ``id_for_label`` attribute to
  462. output the element's ID.
  463. * The ``<textarea>`` tags rendered by :class:`~django.forms.Textarea` now
  464. include a ``maxlength`` attribute if the :class:`~django.db.models.TextField`
  465. model field has a ``max_length``.
  466. * :attr:`Field.choices<django.db.models.Field.choices>` now allows you to
  467. customize the "empty choice" label by including a tuple with an empty string
  468. or ``None`` for the key and the custom label as the value. The default blank
  469. option ``"----------"`` will be omitted in this case.
  470. * :class:`~django.forms.MultiValueField` allows optional subfields by setting
  471. the ``require_all_fields`` argument to ``False``. The ``required`` attribute
  472. for each individual field will be respected, and a new ``incomplete``
  473. validation error will be raised when any required fields are empty.
  474. * The :meth:`~django.forms.Form.clean` method on a form no longer needs to
  475. return ``self.cleaned_data``. If it does return a changed dictionary then
  476. that will still be used.
  477. * After a temporary regression in Django 1.6, it's now possible again to make
  478. :class:`~django.forms.TypedChoiceField` ``coerce`` method return an arbitrary
  479. value.
  480. * :attr:`SelectDateWidget.months
  481. <django.forms.SelectDateWidget.months>` can be used to
  482. customize the wording of the months displayed in the select widget.
  483. * The ``min_num`` and ``validate_min`` parameters were added to
  484. :func:`~django.forms.formsets.formset_factory` to allow validating
  485. a minimum number of submitted forms.
  486. * The metaclasses used by ``Form`` and ``ModelForm`` have been reworked to
  487. support more inheritance scenarios. The previous limitation that prevented
  488. inheriting from both ``Form`` and ``ModelForm`` simultaneously have been
  489. removed as long as ``ModelForm`` appears first in the MRO.
  490. * It's now possible to remove a field from a ``Form`` when subclassing by
  491. setting the name to ``None``.
  492. * It's now possible to customize the error messages for ``ModelForm``’s
  493. ``unique``, ``unique_for_date``, and ``unique_together`` constraints.
  494. In order to support ``unique_together`` or any other ``NON_FIELD_ERROR``,
  495. ``ModelForm`` now looks for the ``NON_FIELD_ERROR`` key in the
  496. ``error_messages`` dictionary of the ``ModelForm``’s inner ``Meta`` class.
  497. See :ref:`considerations regarding model's error_messages
  498. <considerations-regarding-model-errormessages>` for more details.
  499. Internationalization
  500. ^^^^^^^^^^^^^^^^^^^^
  501. * The :attr:`django.middleware.locale.LocaleMiddleware.response_redirect_class`
  502. attribute allows you to customize the redirects issued by the middleware.
  503. * The :class:`~django.middleware.locale.LocaleMiddleware` now stores the user's
  504. selected language with the session key ``_language``. This should only be
  505. accessed using the :data:`~django.utils.translation.LANGUAGE_SESSION_KEY`
  506. constant. Previously it was stored with the key ``django_language`` and the
  507. ``LANGUAGE_SESSION_KEY`` constant did not exist, but keys reserved for Django
  508. should start with an underscore. For backwards compatibility ``django_language``
  509. is still read from in 1.7. Sessions will be migrated to the new key
  510. as they are written.
  511. * The :ttag:`blocktrans` tag now supports a ``trimmed`` option. This
  512. option will remove newline characters from the beginning and the end of the
  513. content of the ``{% blocktrans %}`` tag, replace any whitespace at the
  514. beginning and end of a line and merge all lines into one using a space
  515. character to separate them. This is quite useful for indenting the content of
  516. a ``{% blocktrans %}`` tag without having the indentation characters end up
  517. in the corresponding entry in the PO file, which makes the translation
  518. process easier.
  519. * When you run :djadmin:`makemessages` from the root directory of your project,
  520. any extracted strings will now be automatically distributed to the proper
  521. app or project message file. See :ref:`how-to-create-language-files` for
  522. details.
  523. * The :djadmin:`makemessages` command now always adds the ``--previous``
  524. command line flag to the ``msgmerge`` command, keeping previously translated
  525. strings in po files for fuzzy strings.
  526. * The following settings to adjust the language cookie options were introduced:
  527. :setting:`LANGUAGE_COOKIE_AGE`, :setting:`LANGUAGE_COOKIE_DOMAIN`
  528. and :setting:`LANGUAGE_COOKIE_PATH`.
  529. * Added :ref:`format definitions <format-localization>` for Esperanto.
  530. Management Commands
  531. ^^^^^^^^^^^^^^^^^^^
  532. * The :djadminopt:`--no-color` option for ``django-admin`` allows you to
  533. disable the colorization of management command output.
  534. * The new :djadminopt:`--natural-foreign` and :djadminopt:`--natural-primary`
  535. options for :djadmin:`dumpdata`, and the new ``use_natural_foreign_keys`` and
  536. ``use_natural_primary_keys`` arguments for ``serializers.serialize()``, allow
  537. the use of natural primary keys when serializing.
  538. * It is no longer necessary to provide the cache table name or the
  539. :djadminopt:`--database` option for the :djadmin:`createcachetable` command.
  540. Django takes this information from your settings file. If you have configured
  541. multiple caches or multiple databases, all cache tables are created.
  542. * The :djadmin:`runserver` command received several improvements:
  543. * On Linux systems, if pyinotify_ is installed, the development server will
  544. reload immediately when a file is changed. Previously, it polled the
  545. filesystem for changes every second. That caused a small delay before
  546. reloads and reduced battery life on laptops.
  547. .. _pyinotify: https://pypi.python.org/pypi/pyinotify
  548. * In addition, the development server automatically reloads when a
  549. translation file is updated, i.e. after running
  550. :djadmin:`compilemessages`.
  551. * All HTTP requests are logged to the console, including requests for static
  552. files or ``favicon.ico`` that used to be filtered out.
  553. * Management commands can now produce syntax colored output under Windows if
  554. the ANSICON third-party tool is installed and active.
  555. * :djadmin:`collectstatic` command with symlink option is now supported on
  556. Windows NT 6 (Windows Vista and newer).
  557. * Initial SQL data now works better if the sqlparse_ Python library is
  558. installed.
  559. Note that it's deprecated in favor of the
  560. :class:`~django.db.migrations.operations.RunSQL` operation of migrations,
  561. which benefits from the improved behavior.
  562. .. _sqlparse: https://pypi.python.org/pypi/sqlparse
  563. Models
  564. ^^^^^^
  565. * The :meth:`QuerySet.update_or_create()
  566. <django.db.models.query.QuerySet.update_or_create>` method was added.
  567. * The new :attr:`~django.db.models.Options.default_permissions` model
  568. ``Meta`` option allows you to customize (or disable) creation of the default
  569. add, change, and delete permissions.
  570. * Explicit :class:`~django.db.models.OneToOneField` for
  571. :ref:`multi-table-inheritance` are now discovered in abstract classes.
  572. * It is now possible to avoid creating a backward relation for
  573. :class:`~django.db.models.OneToOneField` by setting its
  574. :attr:`~django.db.models.ForeignKey.related_name` to
  575. ``'+'`` or ending it with ``'+'``.
  576. * :class:`F expressions <django.db.models.F>` support the power operator
  577. (``**``).
  578. * The ``remove()`` and ``clear()`` methods of the related managers created by
  579. ``ForeignKey`` and ``GenericForeignKey`` now accept the ``bulk`` keyword
  580. argument to control whether or not to perform operations in bulk
  581. (i.e. using ``QuerySet.update()``). Defaults to ``True``.
  582. * It is now possible to use ``None`` as a query value for the :lookup:`iexact`
  583. lookup.
  584. * It is now possible to pass a callable as value for the attribute
  585. :attr:`~django.db.models.ForeignKey.limit_choices_to` when defining a
  586. ``ForeignKey`` or ``ManyToManyField``.
  587. * Calling :meth:`only() <django.db.models.query.QuerySet.only>` and
  588. :meth:`defer() <django.db.models.query.QuerySet.defer>` on the result of
  589. :meth:`QuerySet.values() <django.db.models.query.QuerySet.values>` now raises
  590. an error (before that, it would either result in a database error or
  591. incorrect data).
  592. * You can use a single list for :attr:`~django.db.models.Options.index_together`
  593. (rather than a list of lists) when specifying a single set of fields.
  594. * Custom intermediate models having more than one foreign key to any of the
  595. models participating in a many-to-many relationship are now permitted,
  596. provided you explicitly specify which foreign keys should be used by setting
  597. the new :attr:`ManyToManyField.through_fields <django.db.models.ManyToManyField.through_fields>`
  598. argument.
  599. * Assigning a model instance to a non-relation field will now throw an error.
  600. Previously this used to work if the field accepted integers as input as it
  601. took the primary key.
  602. * Integer fields are now validated against database backend specific min and
  603. max values based on their :meth:`internal_type <django.db.models.Field.get_internal_type>`.
  604. Previously model field validation didn't prevent values out of their associated
  605. column data type range from being saved resulting in an integrity error.
  606. * It is now possible to explicitly :meth:`~django.db.models.query.QuerySet.order_by`
  607. a relation ``_id`` field by using its attribute name.
  608. Signals
  609. ^^^^^^^
  610. * The ``enter`` argument was added to the
  611. :data:`~django.test.signals.setting_changed` signal.
  612. * The model signals can be now be connected to using a ``str`` of the
  613. ``'app_label.ModelName'`` form – just like related fields – to lazily
  614. reference their senders.
  615. Templates
  616. ^^^^^^^^^
  617. * The :meth:`Context.push() <django.template.Context.push>` method now returns
  618. a context manager which automatically calls :meth:`pop()
  619. <django.template.Context.pop>` upon exiting the ``with`` statement.
  620. Additionally, :meth:`push() <django.template.Context.push>` now accepts
  621. parameters that are passed to the ``dict`` constructor used to build the new
  622. context level.
  623. * The new :meth:`Context.flatten() <django.template.Context.flatten>` method
  624. returns a ``Context``'s stack as one flat dictionary.
  625. * ``Context`` objects can now be compared for equality (internally, this
  626. uses :meth:`Context.flatten() <django.template.Context.flatten>` so the
  627. internal structure of each ``Context``'s stack doesn't matter as long as their
  628. flattened version is identical).
  629. * The :ttag:`widthratio` template tag now accepts an ``"as"`` parameter to
  630. capture the result in a variable.
  631. * The :ttag:`include` template tag will now also accept anything with a
  632. ``render()`` method (such as a ``Template``) as an argument. String
  633. arguments will be looked up using
  634. :func:`~django.template.loader.get_template` as always.
  635. * It is now possible to :ttag:`include` templates recursively.
  636. * Template objects now have an origin attribute set when
  637. ``TEMPLATE_DEBUG`` is ``True``. This allows template origins to be
  638. inspected and logged outside of the ``django.template`` infrastructure.
  639. * ``TypeError`` exceptions are no longer silenced when raised during the
  640. rendering of a template.
  641. * The following functions now accept a ``dirs`` parameter which is a list or
  642. tuple to override ``TEMPLATE_DIRS``:
  643. * :func:`django.template.loader.get_template()`
  644. * :func:`django.template.loader.select_template()`
  645. * :func:`django.shortcuts.render()`
  646. * :func:`django.shortcuts.render_to_response()`
  647. * The :tfilter:`time` filter now accepts timezone-related :ref:`format
  648. specifiers <date-and-time-formatting-specifiers>` ``'e'``, ``'O'`` , ``'T'``
  649. and ``'Z'`` and is able to digest :ref:`time-zone-aware
  650. <naive_vs_aware_datetimes>` ``datetime`` instances performing the expected
  651. rendering.
  652. * The :ttag:`cache` tag will now try to use the cache called
  653. "template_fragments" if it exists and fall back to using the default cache
  654. otherwise. It also now accepts an optional ``using`` keyword argument to
  655. control which cache it uses.
  656. * The new :tfilter:`truncatechars_html` filter truncates a string to be no
  657. longer than the specified number of characters, taking HTML into account.
  658. Requests and Responses
  659. ^^^^^^^^^^^^^^^^^^^^^^
  660. * The new :attr:`HttpRequest.scheme <django.http.HttpRequest.scheme>` attribute
  661. specifies the scheme of the request (``http`` or ``https`` normally).
  662. * The shortcut :func:`redirect() <django.shortcuts.redirect>` now supports
  663. relative URLs.
  664. * The new :class:`~django.http.JsonResponse` subclass of
  665. :class:`~django.http.HttpResponse` helps easily create JSON-encoded responses.
  666. Tests
  667. ^^^^^
  668. * :class:`~django.test.runner.DiscoverRunner` has two new attributes,
  669. :attr:`~django.test.runner.DiscoverRunner.test_suite` and
  670. :attr:`~django.test.runner.DiscoverRunner.test_runner`, which facilitate
  671. overriding the way tests are collected and run.
  672. * The ``fetch_redirect_response`` argument was added to
  673. :meth:`~django.test.SimpleTestCase.assertRedirects`. Since the test
  674. client can't fetch externals URLs, this allows you to use ``assertRedirects``
  675. with redirects that aren't part of your Django app.
  676. * Correct handling of scheme when making comparisons in
  677. :meth:`~django.test.SimpleTestCase.assertRedirects`.
  678. * The ``secure`` argument was added to all the request methods of
  679. :class:`~django.test.Client`. If ``True``, the request will be made
  680. through HTTPS.
  681. * :meth:`~django.test.TransactionTestCase.assertNumQueries` now prints
  682. out the list of executed queries if the assertion fails.
  683. * The ``WSGIRequest`` instance generated by the test handler is now attached to
  684. the :attr:`django.test.Response.wsgi_request` attribute.
  685. * The database settings for testing have been collected into a dictionary
  686. named :setting:`TEST <DATABASE-TEST>`.
  687. Utilities
  688. ^^^^^^^^^
  689. * Improved :func:`~django.utils.html.strip_tags` accuracy (but it still cannot
  690. guarantee an HTML-safe result, as stated in the documentation).
  691. Validators
  692. ^^^^^^^^^^
  693. * :class:`~django.core.validators.RegexValidator` now accepts the optional
  694. :attr:`~django.core.validators.RegexValidator.flags` and
  695. Boolean :attr:`~django.core.validators.RegexValidator.inverse_match` arguments.
  696. The :attr:`~django.core.validators.RegexValidator.inverse_match` attribute
  697. determines if the :exc:`~django.core.exceptions.ValidationError` should
  698. be raised when the regular expression pattern matches (``True``) or does not
  699. match (``False``, by default) the provided ``value``. The
  700. :attr:`~django.core.validators.RegexValidator.flags` attribute sets the flags
  701. used when compiling a regular expression string.
  702. * :class:`~django.core.validators.URLValidator` now accepts an optional
  703. ``schemes`` argument which allows customization of the accepted URI schemes
  704. (instead of the defaults ``http(s)`` and ``ftp(s)``).
  705. * :func:`~django.core.validators.validate_email` now accepts addresses with
  706. IPv6 literals, like ``example@[2001:db8::1]``, as specified in RFC 5321.
  707. Backwards incompatible changes in 1.7
  708. =====================================
  709. .. warning::
  710. In addition to the changes outlined in this section, be sure to review the
  711. :ref:`deprecation plan <deprecation-removed-in-1.7>` for any features that
  712. have been removed. If you haven't updated your code within the
  713. deprecation timeline for a given feature, its removal may appear as a
  714. backwards incompatible change.
  715. ``allow_syncdb`` / ``allow_migrate``
  716. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  717. While Django will still look at ``allow_syncdb`` methods even though they
  718. should be renamed to ``allow_migrate``, there is a subtle difference in which
  719. models get passed to these methods.
  720. For apps with migrations, ``allow_migrate`` will now get passed
  721. :ref:`historical models <historical-models>`, which are special versioned models
  722. without custom attributes, methods or managers. Make sure your ``allow_migrate``
  723. methods are only referring to fields or other items in ``model._meta``.
  724. initial_data
  725. ~~~~~~~~~~~~
  726. Apps with migrations will not load ``initial_data`` fixtures when they have
  727. finished migrating. Apps without migrations will continue to load these fixtures
  728. during the phase of ``migrate`` which emulates the old ``syncdb`` behavior,
  729. but any new apps will not have this support.
  730. Instead, you are encouraged to load initial data in migrations if you need it
  731. (using the ``RunPython`` operation and your model classes);
  732. this has the added advantage that your initial data will not need updating
  733. every time you change the schema.
  734. Additionally, like the rest of Django's old ``syncdb`` code, ``initial_data``
  735. has been started down the deprecation path and will be removed in Django 1.9.
  736. deconstruct() and serializability
  737. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  738. Django now requires all Field classes and all of their constructor arguments
  739. to be serializable. If you modify the constructor signature in your custom
  740. Field in any way, you'll need to implement a deconstruct() method;
  741. we've expanded the custom field documentation with :ref:`instructions
  742. on implementing this method <custom-field-deconstruct-method>`.
  743. The requirement for all field arguments to be
  744. :ref:`serializable <migration-serializing>` means that any custom class
  745. instances being passed into Field constructors - things like custom Storage
  746. subclasses, for instance - need to have a :ref:`deconstruct method defined on
  747. them as well <custom-deconstruct-method>`, though Django provides a handy
  748. class decorator that will work for most applications.
  749. App-loading changes
  750. ~~~~~~~~~~~~~~~~~~~
  751. Start-up sequence
  752. ^^^^^^^^^^^^^^^^^
  753. Django 1.7 loads application configurations and models as soon as it starts.
  754. While this behavior is more straightforward and is believed to be more robust,
  755. regressions cannot be ruled out. See :ref:`applications-troubleshooting` for
  756. solutions to some problems you may encounter.
  757. Standalone scripts
  758. ^^^^^^^^^^^^^^^^^^
  759. If you're using Django in a plain Python script — rather than a management
  760. command — and you rely on the :envvar:`DJANGO_SETTINGS_MODULE` environment
  761. variable, you must now explicitly initialize Django at the beginning of your
  762. script with::
  763. >>> import django
  764. >>> django.setup()
  765. Otherwise, you will hit an ``AppRegistryNotReady`` exception.
  766. WSGI scripts
  767. ^^^^^^^^^^^^
  768. Until Django 1.3, the recommended way to create a WSGI application was::
  769. import django.core.handlers.wsgi
  770. application = django.core.handlers.wsgi.WSGIHandler()
  771. In Django 1.4, support for WSGI was improved and the API changed to::
  772. from django.core.wsgi import get_wsgi_application
  773. application = get_wsgi_application()
  774. If you're still using the former style in your WSGI script, you need to
  775. upgrade to the latter, or you will hit an ``AppRegistryNotReady`` exception.
  776. App registry consistency
  777. ^^^^^^^^^^^^^^^^^^^^^^^^
  778. It is no longer possible to have multiple installed applications with the same
  779. label. In previous versions of Django, this didn't always work correctly, but
  780. didn't crash outright either.
  781. If you have two apps with the same label, you should create an
  782. :class:`~django.apps.AppConfig` for one of them and override its
  783. :class:`~django.apps.AppConfig.label` there. You should then adjust your code
  784. wherever it references this application or its models with the old label.
  785. It isn't possible to import the same model twice through different paths any
  786. more. As of Django 1.6, this may happen only if you're manually putting a
  787. directory and a subdirectory on :envvar:`PYTHONPATH`. Refer to the section on
  788. the new project layout in the :doc:`1.4 release notes </releases/1.4>` for
  789. migration instructions.
  790. You should make sure that:
  791. * All models are defined in applications that are listed in
  792. :setting:`INSTALLED_APPS` or have an explicit
  793. :attr:`~django.db.models.Options.app_label`.
  794. * Models aren't imported as a side-effect of loading their application.
  795. Specifically, you shouldn't import models in the root module of an
  796. application nor in the module that define its configuration class.
  797. Django will enforce these requirements as of version 1.9, after a deprecation
  798. period.
  799. Subclassing AppCommand
  800. ^^^^^^^^^^^^^^^^^^^^^^
  801. Subclasses of :class:`~django.core.management.AppCommand` must now implement a
  802. :meth:`~django.core.management.AppCommand.handle_app_config` method instead of
  803. ``handle_app()``. This method receives an :class:`~django.apps.AppConfig`
  804. instance instead of a models module.
  805. Introspecting applications
  806. ^^^^^^^^^^^^^^^^^^^^^^^^^^
  807. Since :setting:`INSTALLED_APPS` now supports application configuration classes
  808. in addition to application modules, you should review code that accesses this
  809. setting directly and use the app registry (:attr:`django.apps.apps`) instead.
  810. The app registry has preserved some features of the old app cache. Even though
  811. the app cache was a private API, obsolete methods and arguments will be
  812. removed through a standard deprecation path, with the exception of the
  813. following changes that take effect immediately:
  814. * ``get_model`` raises :exc:`LookupError` instead of returning ``None`` when no
  815. model is found.
  816. * The ``only_installed`` argument of ``get_model`` and ``get_models`` no
  817. longer exists, nor does the ``seed_cache`` argument of ``get_model``.
  818. Management commands and order of :setting:`INSTALLED_APPS`
  819. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  820. When several applications provide management commands with the same name,
  821. Django loads the command from the application that comes first in
  822. :setting:`INSTALLED_APPS`. Previous versions loaded the command from the
  823. application that came last.
  824. This brings discovery of management commands in line with other parts of
  825. Django that rely on the order of :setting:`INSTALLED_APPS`, such as static
  826. files, templates, and translations.
  827. .. _validation-error-constructor-and-internal-storage:
  828. ``ValidationError`` constructor and internal storage
  829. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  830. The behavior of the ``ValidationError`` constructor has changed when it
  831. receives a container of errors as an argument (e.g. a ``list`` or an
  832. ``ErrorList``):
  833. * It converts any strings it finds to instances of ``ValidationError``
  834. before adding them to its internal storage.
  835. * It doesn't store the given container but rather copies its content to its
  836. own internal storage; previously the container itself was added to the
  837. ``ValidationError`` instance and used as internal storage.
  838. This means that if you access the ``ValidationError`` internal storages, such
  839. as ``error_list``; ``error_dict``; or the return value of
  840. ``update_error_dict()`` you may find instances of ``ValidationError`` where you
  841. would have previously found strings.
  842. Also if you directly assigned the return value of ``update_error_dict()``
  843. to ``Form._errors`` you may inadvertently add `list` instances where
  844. ``ErrorList`` instances are expected. This is a problem because unlike a
  845. simple `list`, an ``ErrorList`` knows how to handle instances of
  846. ``ValidationError``.
  847. Most use-cases that warranted using these private APIs are now covered by
  848. the newly introduced :meth:`Form.add_error() <django.forms.Form.add_error()>`
  849. method::
  850. # Old pattern:
  851. try:
  852. # ...
  853. except ValidationError as e:
  854. self._errors = e.update_error_dict(self._errors)
  855. # New pattern:
  856. try:
  857. # ...
  858. except ValidationError as e:
  859. self.add_error(None, e)
  860. If you need both Django <= 1.6 and 1.7 compatibility you can't use
  861. :meth:`Form.add_error() <django.forms.Form.add_error()>` since it
  862. wasn't available before Django 1.7, but you can use the following
  863. workaround to convert any ``list`` into ``ErrorList``::
  864. try:
  865. # ...
  866. except ValidationError as e:
  867. self._errors = e.update_error_dict(self._errors)
  868. # Additional code to ensure ``ErrorDict`` is exclusively
  869. # composed of ``ErrorList`` instances.
  870. for field, error_list in self._errors.items():
  871. if not isinstance(error_list, self.error_class):
  872. self._errors[field] = self.error_class(error_list)
  873. Behavior of ``LocMemCache`` regarding pickle errors
  874. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  875. An inconsistency existed in previous versions of Django regarding how pickle
  876. errors are handled by different cache backends.
  877. ``django.core.cache.backends.locmem.LocMemCache`` used to fail silently when
  878. such an error occurs, which is inconsistent with other backends and leads to
  879. cache-specific errors. This has been fixed in Django 1.7, see
  880. :ticket:`21200` for more details.
  881. Cache keys are now generated from the request's absolute URL
  882. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  883. Previous versions of Django generated cache keys using a request's path and
  884. query string but not the scheme or host. If a Django application was serving
  885. multiple subdomains or domains, cache keys could collide. In Django 1.7, cache
  886. keys vary by the absolute URL of the request including scheme, host, path, and
  887. query string. For example, the URL portion of a cache key is now generated from
  888. ``http://www.example.com/path/to/?key=val`` rather than ``/path/to/?key=val``.
  889. The cache keys generated by Django 1.7 will be different from the keys
  890. generated by older versions of Django. After upgrading to Django 1.7, the first
  891. request to any previously cached URL will be a cache miss.
  892. Passing ``None`` to ``Manager.db_manager()``
  893. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  894. In previous versions of Django, it was possible to use
  895. ``db_manager(using=None)`` on a model manager instance to obtain a manager
  896. instance using default routing behavior, overriding any manually specified
  897. database routing. In Django 1.7, a value of ``None`` passed to db_manager will
  898. produce a router that *retains* any manually assigned database routing -- the
  899. manager will *not* be reset. This was necessary to resolve an inconsistency in
  900. the way routing information cascaded over joins. See :ticket:`13724` for more
  901. details.
  902. pytz may be required
  903. ~~~~~~~~~~~~~~~~~~~~
  904. If your project handles datetimes before 1970 or after 2037 and Django raises
  905. a :exc:`ValueError` when encountering them, you will have to install pytz_. You
  906. may be affected by this problem if you use Django's time zone-related date
  907. formats or :mod:`django.contrib.syndication`.
  908. .. _pytz: https://pypi.python.org/pypi/pytz/
  909. ``remove()`` and ``clear()`` methods of related managers
  910. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  911. The ``remove()`` and ``clear()`` methods of the related managers created by
  912. ``ForeignKey``, ``GenericForeignKey``, and ``ManyToManyField`` suffered from a
  913. number of issues. Some operations ran multiple data modifying queries without
  914. wrapping them in a transaction, and some operations didn't respect default
  915. filtering when it was present (i.e. when the default manager on the related
  916. model implemented a custom ``get_queryset()``).
  917. Fixing the issues introduced some backward incompatible changes:
  918. - The default implementation of ``remove()`` for ``ForeignKey`` related managers
  919. changed from a series of ``Model.save()`` calls to a single
  920. ``QuerySet.update()`` call. The change means that ``pre_save`` and
  921. ``post_save`` signals aren't sent anymore. You can use the ``bulk=False``
  922. keyword argument to revert to the previous behavior.
  923. - The ``remove()`` and ``clear()`` methods for ``GenericForeignKey`` related
  924. managers now perform bulk delete. The ``Model.delete()`` method isn't called
  925. on each instance anymore. You can use the ``bulk=False`` keyword argument to
  926. revert to the previous behavior.
  927. - The ``remove()`` and ``clear()`` methods for ``ManyToManyField`` related
  928. managers perform nested queries when filtering is involved, which may or
  929. may not be an issue depending on your database and your data itself.
  930. See :ref:`this note <nested-queries-performance>` for more details.
  931. Admin login redirection strategy
  932. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  933. Historically, the Django admin site passed the request from an unauthorized or
  934. unauthenticated user directly to the login view, without HTTP redirection. In
  935. Django 1.7, this behavior changed to conform to a more traditional workflow
  936. where any unauthorized request to an admin page will be redirected (by HTTP
  937. status code 302) to the login page, with the ``next`` parameter set to the
  938. referring path. The user will be redirected there after a successful login.
  939. Note also that the admin login form has been updated to not contain the
  940. ``this_is_the_login_form`` field (now unused) and the ``ValidationError`` code
  941. has been set to the more regular ``invalid_login`` key.
  942. ``select_for_update()`` requires a transaction
  943. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  944. Historically, queries that use
  945. :meth:`~django.db.models.query.QuerySet.select_for_update()` could be
  946. executed in autocommit mode, outside of a transaction. Before Django
  947. 1.6, Django's automatic transactions mode allowed this to be used to
  948. lock records until the next write operation. Django 1.6 introduced
  949. database-level autocommit; since then, execution in such a context
  950. voids the effect of ``select_for_update()``. It is, therefore, assumed
  951. now to be an error and raises an exception.
  952. This change was made because such errors can be caused by including an
  953. app which expects global transactions (e.g. :setting:`ATOMIC_REQUESTS
  954. <DATABASE-ATOMIC_REQUESTS>` set to ``True``), or Django's old autocommit
  955. behavior, in a project which runs without them; and further, such
  956. errors may manifest as data-corruption bugs. It was also made in
  957. Django 1.6.3.
  958. This change may cause test failures if you use ``select_for_update()``
  959. in a test class which is a subclass of
  960. :class:`~django.test.TransactionTestCase` rather than
  961. :class:`~django.test.TestCase`.
  962. Contrib middleware removed from default :setting:`MIDDLEWARE_CLASSES`
  963. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  964. The :ref:`app-loading refactor <app-loading-refactor-17-release-note>`
  965. deprecated using models from apps which are not part of the
  966. :setting:`INSTALLED_APPS` setting. This exposed an incompatibility between
  967. the default :setting:`INSTALLED_APPS` and :setting:`MIDDLEWARE_CLASSES` in the
  968. global defaults (``django.conf.global_settings``). To bring these settings in
  969. sync and prevent deprecation warnings when doing things like testing reusable
  970. apps with minimal settings,
  971. :class:`~django.contrib.sessions.middleware.SessionMiddleware`,
  972. :class:`~django.contrib.auth.middleware.AuthenticationMiddleware`, and
  973. :class:`~django.contrib.messages.middleware.MessageMiddleware` were removed
  974. from the defaults. These classes will still be included in the default settings
  975. generated by :djadmin:`startproject`. Most projects will not be affected by
  976. this change but if you were not previously declaring the
  977. :setting:`MIDDLEWARE_CLASSES` in your project settings and relying on the
  978. global default you should ensure that the new defaults are in line with your
  979. project's needs. You should also check for any code that accesses
  980. ``django.conf.global_settings.MIDDLEWARE_CLASSES`` directly.
  981. Miscellaneous
  982. ~~~~~~~~~~~~~
  983. * The :meth:`django.core.files.uploadhandler.FileUploadHandler.new_file()`
  984. method is now passed an additional ``content_type_extra`` parameter. If you
  985. have a custom :class:`~django.core.files.uploadhandler.FileUploadHandler`
  986. that implements ``new_file()``, be sure it accepts this new parameter.
  987. * :class:`ModelFormSet<django.forms.models.BaseModelFormSet>`\s no longer
  988. delete instances when ``save(commit=False)`` is called. See
  989. :attr:`~django.forms.formsets.BaseFormSet.can_delete` for instructions on how
  990. to manually delete objects from deleted forms.
  991. * Loading empty fixtures emits a ``RuntimeWarning`` rather than raising
  992. :class:`~django.core.management.CommandError`.
  993. * :func:`django.contrib.staticfiles.views.serve` will now raise an
  994. :exc:`~django.http.Http404` exception instead of
  995. :exc:`~django.core.exceptions.ImproperlyConfigured` when :setting:`DEBUG`
  996. is ``False``. This change removes the need to conditionally add the view to
  997. your root URLconf, which in turn makes it safe to reverse by name. It also
  998. removes the ability for visitors to generate spurious HTTP 500 errors by
  999. requesting static files that don't exist or haven't been collected yet.
  1000. * The :meth:`django.db.models.Model.__eq__` method is now defined in a
  1001. way where instances of a proxy model and its base model are considered
  1002. equal when primary keys match. Previously only instances of exact same
  1003. class were considered equal on primary key match.
  1004. * The :meth:`django.db.models.Model.__eq__` method has changed such that
  1005. two ``Model`` instances without primary key values won't be considered
  1006. equal (unless they are the same instance).
  1007. * The :meth:`django.db.models.Model.__hash__` method will now raise ``TypeError``
  1008. when called on an instance without a primary key value. This is done to
  1009. avoid mutable ``__hash__`` values in containers.
  1010. * :class:`~django.db.models.AutoField` columns in SQLite databases will now be
  1011. created using the ``AUTOINCREMENT`` option, which guarantees monotonic
  1012. increments. This will cause primary key numbering behavior to change on
  1013. SQLite, becoming consistent with most other SQL databases. This will only
  1014. apply to newly created tables. If you have a database created with an older
  1015. version of Django, you will need to migrate it to take advantage of this
  1016. feature. For example, you could do the following:
  1017. #) Use :djadmin:`dumpdata` to save your data.
  1018. #) Rename the existing database file (keep it as a backup).
  1019. #) Run :djadmin:`migrate` to create the updated schema.
  1020. #) Use :djadmin:`loaddata` to import the fixtures you exported in (1).
  1021. * ``django.contrib.auth.models.AbstractUser`` no longer defines a
  1022. :meth:`~django.db.models.Model.get_absolute_url()` method. The old definition
  1023. returned ``"/users/%s/" % urlquote(self.username)`` which was arbitrary
  1024. since applications may or may not define such a url in ``urlpatterns``.
  1025. Define a ``get_absolute_url()`` method on your own custom user object or use
  1026. :setting:`ABSOLUTE_URL_OVERRIDES` if you want a URL for your user.
  1027. * The static asset-serving functionality of the
  1028. :class:`django.test.LiveServerTestCase` class has been simplified: Now it's
  1029. only able to serve content already present in :setting:`STATIC_ROOT` when
  1030. tests are run. The ability to transparently serve all the static assets
  1031. (similarly to what one gets with :setting:`DEBUG = True <DEBUG>` at
  1032. development-time) has been moved to a new class that lives in the
  1033. ``staticfiles`` application (the one actually in charge of such feature):
  1034. :class:`django.contrib.staticfiles.testing.StaticLiveServerTestCase`. In other
  1035. words, ``LiveServerTestCase`` itself is less powerful but at the same time
  1036. has less magic.
  1037. Rationale behind this is removal of dependency of non-contrib code on
  1038. contrib applications.
  1039. * The old cache URI syntax (e.g. ``"locmem://"``) is no longer supported. It
  1040. still worked, even though it was not documented or officially supported. If
  1041. you're still using it, please update to the current :setting:`CACHES` syntax.
  1042. * The default ordering of ``Form`` fields in case of inheritance has changed to
  1043. follow normal Python MRO. Fields are now discovered by iterating through the
  1044. MRO in reverse with the topmost class coming last. This only affects you if
  1045. you relied on the default field ordering while having fields defined on both
  1046. the current class *and* on a parent ``Form``.
  1047. * The ``required`` argument of
  1048. :class:`~django.forms.SelectDateWidget` has been removed.
  1049. This widget now respects the form field's ``is_required`` attribute like
  1050. other widgets.
  1051. * ``Widget.is_hidden`` is now a read-only property, getting its value by
  1052. introspecting the presence of ``input_type == 'hidden'``.
  1053. * :meth:`~django.db.models.query.QuerySet.select_related` now chains in the
  1054. same way as other similar calls like ``prefetch_related``. That is,
  1055. ``select_related('foo', 'bar')`` is equivalent to
  1056. ``select_related('foo').select_related('bar')``. Previously the latter would
  1057. have been equivalent to ``select_related('bar')``.
  1058. * GeoDjango dropped support for GEOS < 3.1.
  1059. * The ``init_connection_state`` method of database backends now executes in
  1060. autocommit mode (unless you set :setting:`AUTOCOMMIT <DATABASE-AUTOCOMMIT>`
  1061. to ``False``). If you maintain a custom database backend, you should check
  1062. that method.
  1063. * The ``django.db.backends.BaseDatabaseFeatures.allows_primary_key_0``
  1064. attribute has been renamed to ``allows_auto_pk_0`` to better describe it.
  1065. It's ``True`` for all database backends included with Django except MySQL
  1066. which does allow primary keys with value 0. It only forbids *autoincrement*
  1067. primary keys with value 0.
  1068. * Shadowing model fields defined in a parent model has been forbidden as this
  1069. creates ambiguity in the expected model behavior. In addition, clashing
  1070. fields in the model inheritance hierarchy result in a system check error.
  1071. For example, if you use multi-inheritance, you need to define custom primary
  1072. key fields on parent models, otherwise the default ``id`` fields will clash.
  1073. See :ref:`model-multiple-inheritance-topic` for details.
  1074. * ``django.utils.translation.parse_accept_lang_header()`` now returns
  1075. lowercase locales, instead of the case as it was provided. As locales should
  1076. be treated case-insensitive this allows us to speed up locale detection.
  1077. * ``django.utils.translation.get_language_from_path()`` and
  1078. ``django.utils.translation.trans_real.get_supported_language_variant()``
  1079. now no longer have a ``supported`` argument.
  1080. * The ``shortcut`` view in ``django.contrib.contenttypes.views`` now supports
  1081. protocol-relative URLs (e.g. ``//example.com``).
  1082. * :class:`~django.contrib.contenttypes.fields.GenericRelation` now supports an
  1083. optional ``related_query_name`` argument. Setting ``related_query_name`` adds
  1084. a relation from the related object back to the content type for filtering,
  1085. ordering and other query operations.
  1086. * When running tests on PostgreSQL, the :setting:`USER` will need read access
  1087. to the built-in ``postgres`` database. This is in lieu of the previous
  1088. behavior of connecting to the actual non-test database.
  1089. * As part of the :doc:`System check framework </ref/checks>`, :ref:`fields,
  1090. models, and model managers <field-checking>` all implement a ``check()``
  1091. method that is registered with the check framework. If you have an existing
  1092. method called ``check()`` on one of these objects, you will need to rename it.
  1093. * As noted above in the "Cache" section of "Minor Features", defining the
  1094. :setting:`TIMEOUT <CACHES-TIMEOUT>` argument of the
  1095. :setting:`CACHES` setting as ``None`` will set the cache keys as
  1096. "non-expiring". Previously, with the memcache backend, a
  1097. :setting:`TIMEOUT <CACHES-TIMEOUT>` of ``0`` would set non-expiring keys,
  1098. but this was inconsistent with the set-and-expire (i.e. no caching) behavior
  1099. of ``set("key", "value", timeout=0)``. If you want non-expiring keys,
  1100. please update your settings to use ``None`` instead of ``0`` as the latter
  1101. now designates set-and-expire in the settings as well.
  1102. * The ``sql*`` management commands now respect the ``allow_migrate()`` method
  1103. of :setting:`DATABASE_ROUTERS`. If you have models synced to non-default
  1104. databases, use the :djadminopt:`--database` flag to get SQL for those
  1105. models (previously they would always be included in the output).
  1106. * Decoding the query string from URLs now falls back to the ISO-8859-1 encoding
  1107. when the input is not valid UTF-8.
  1108. * With the addition of the
  1109. ``django.contrib.auth.middleware.SessionAuthenticationMiddleware`` to
  1110. the default project template (pre-1.7.2 only), a database must be created
  1111. before accessing a page using :djadmin:`runserver`.
  1112. .. _deprecated-features-1.7:
  1113. Features deprecated in 1.7
  1114. ==========================
  1115. ``django.core.cache.get_cache``
  1116. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1117. ``django.core.cache.get_cache`` has been supplanted by
  1118. :data:`django.core.cache.caches`.
  1119. ``django.utils.dictconfig``/``django.utils.importlib``
  1120. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1121. ``django.utils.dictconfig`` and ``django.utils.importlib`` were copies of
  1122. respectively :mod:`logging.config` and :mod:`importlib` provided for Python
  1123. versions prior to 2.7. They have been deprecated.
  1124. ``django.utils.module_loading.import_by_path``
  1125. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1126. The current ``django.utils.module_loading.import_by_path`` function
  1127. catches ``AttributeError``, ``ImportError``, and ``ValueError`` exceptions,
  1128. and re-raises :exc:`~django.core.exceptions.ImproperlyConfigured`. Such
  1129. exception masking makes it needlessly hard to diagnose circular import
  1130. problems, because it makes it look like the problem comes from inside Django.
  1131. It has been deprecated in favor of
  1132. :meth:`~django.utils.module_loading.import_string`.
  1133. ``django.utils.tzinfo``
  1134. ~~~~~~~~~~~~~~~~~~~~~~~
  1135. ``django.utils.tzinfo`` provided two :class:`~datetime.tzinfo` subclasses,
  1136. ``LocalTimezone`` and ``FixedOffset``. They've been deprecated in favor of
  1137. more correct alternatives provided by :mod:`django.utils.timezone`,
  1138. :func:`django.utils.timezone.get_default_timezone` and
  1139. :func:`django.utils.timezone.get_fixed_timezone`.
  1140. ``django.utils.unittest``
  1141. ~~~~~~~~~~~~~~~~~~~~~~~~~
  1142. ``django.utils.unittest`` provided uniform access to the ``unittest2`` library
  1143. on all Python versions. Since ``unittest2`` became the standard library's
  1144. :mod:`unittest` module in Python 2.7, and Django 1.7 drops support for older
  1145. Python versions, this module isn't useful anymore. It has been deprecated. Use
  1146. :mod:`unittest` instead.
  1147. ``django.utils.datastructures.SortedDict``
  1148. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1149. As :class:`~collections.OrderedDict` was added to the standard library in
  1150. Python 2.7, ``SortedDict`` is no longer needed and has been deprecated.
  1151. The two additional, deprecated methods provided by ``SortedDict`` (``insert()``
  1152. and ``value_for_index()``) have been removed. If you relied on these methods to
  1153. alter structures like form fields, you should now treat these ``OrderedDict``\s
  1154. as immutable objects and override them to change their content.
  1155. For example, you might want to override ``MyFormClass.base_fields`` (although
  1156. this attribute isn't considered a public API) to change the ordering of fields
  1157. for all ``MyFormClass`` instances; or similarly, you could override
  1158. ``self.fields`` from inside ``MyFormClass.__init__()``, to change the fields
  1159. for a particular form instance. For example (from Django itself)::
  1160. PasswordChangeForm.base_fields = OrderedDict(
  1161. (k, PasswordChangeForm.base_fields[k])
  1162. for k in ['old_password', 'new_password1', 'new_password2']
  1163. )
  1164. Custom SQL location for models package
  1165. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1166. Previously, if models were organized in a package (``myapp/models/``) rather
  1167. than simply ``myapp/models.py``, Django would look for initial SQL data in
  1168. ``myapp/models/sql/``. This bug has been fixed so that Django
  1169. will search ``myapp/sql/`` as documented. After this issue was fixed, migrations
  1170. were added which deprecates initial SQL data. Thus, while this change still
  1171. exists, the deprecation is irrelevant as the entire feature will be removed in
  1172. Django 1.9.
  1173. Reorganization of ``django.contrib.sites``
  1174. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1175. ``django.contrib.sites`` provides reduced functionality when it isn't in
  1176. :setting:`INSTALLED_APPS`. The app-loading refactor adds some constraints in
  1177. that situation. As a consequence, two objects were moved, and the old
  1178. locations are deprecated:
  1179. * :class:`~django.contrib.sites.requests.RequestSite` now lives in
  1180. ``django.contrib.sites.requests``.
  1181. * :func:`~django.contrib.sites.shortcuts.get_current_site` now lives in
  1182. ``django.contrib.sites.shortcuts``.
  1183. ``declared_fieldsets`` attribute on ``ModelAdmin``
  1184. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1185. ``ModelAdmin.declared_fieldsets`` has been deprecated. Despite being a private
  1186. API, it will go through a regular deprecation path. This attribute was mostly
  1187. used by methods that bypassed ``ModelAdmin.get_fieldsets()`` but this was
  1188. considered a bug and has been addressed.
  1189. Reorganization of ``django.contrib.contenttypes``
  1190. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1191. Since ``django.contrib.contenttypes.generic`` defined both admin and model
  1192. related objects, an import of this module could trigger unexpected side effects.
  1193. As a consequence, its contents were split into :mod:`~django.contrib.contenttypes`
  1194. submodules and the ``django.contrib.contenttypes.generic`` module is deprecated:
  1195. * :class:`~django.contrib.contenttypes.fields.GenericForeignKey` and
  1196. :class:`~django.contrib.contenttypes.fields.GenericRelation` now live in
  1197. :mod:`~django.contrib.contenttypes.fields`.
  1198. * :class:`~django.contrib.contenttypes.forms.BaseGenericInlineFormSet` and
  1199. :func:`~django.contrib.contenttypes.forms.generic_inlineformset_factory` now
  1200. live in :mod:`~django.contrib.contenttypes.forms`.
  1201. * :class:`~django.contrib.contenttypes.admin.GenericInlineModelAdmin`,
  1202. :class:`~django.contrib.contenttypes.admin.GenericStackedInline` and
  1203. :class:`~django.contrib.contenttypes.admin.GenericTabularInline` now live in
  1204. :mod:`~django.contrib.contenttypes.admin`.
  1205. ``syncdb``
  1206. ~~~~~~~~~~
  1207. The ``syncdb`` command has been deprecated in favor of the new :djadmin:`migrate`
  1208. command. ``migrate`` takes the same arguments as ``syncdb`` used to plus a few
  1209. more, so it's safe to just change the name you're calling and nothing else.
  1210. ``util`` modules renamed to ``utils``
  1211. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1212. The following instances of ``util.py`` in the Django codebase have been renamed
  1213. to ``utils.py`` in an effort to unify all util and utils references:
  1214. * ``django.contrib.admin.util``
  1215. * ``django.contrib.gis.db.backends.util``
  1216. * ``django.db.backends.util``
  1217. * ``django.forms.util``
  1218. ``get_formsets`` method on ``ModelAdmin``
  1219. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1220. ``ModelAdmin.get_formsets`` has been deprecated in favor of the new
  1221. :meth:`~django.contrib.admin.ModelAdmin.get_formsets_with_inlines`, in order to
  1222. better handle the case of selectively showing inlines on a ``ModelAdmin``.
  1223. ``IPAddressField``
  1224. ~~~~~~~~~~~~~~~~~~
  1225. The ``django.db.models.IPAddressField`` and ``django.forms.IPAddressField``
  1226. fields have been deprecated in favor of
  1227. :class:`django.db.models.GenericIPAddressField` and
  1228. :class:`django.forms.GenericIPAddressField`.
  1229. ``BaseMemcachedCache._get_memcache_timeout`` method
  1230. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1231. The ``BaseMemcachedCache._get_memcache_timeout()`` method has been renamed to
  1232. ``get_backend_timeout()``. Despite being a private API, it will go through the
  1233. normal deprecation.
  1234. Natural key serialization options
  1235. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1236. The ``--natural`` and ``-n`` options for :djadmin:`dumpdata` have been
  1237. deprecated. Use :djadminopt:`--natural-foreign` instead.
  1238. Similarly, the ``use_natural_keys`` argument for ``serializers.serialize()``
  1239. has been deprecated. Use ``use_natural_foreign_keys`` instead.
  1240. Merging of ``POST`` and ``GET`` arguments into ``WSGIRequest.REQUEST``
  1241. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1242. It was already strongly suggested that you use ``GET`` and ``POST`` instead of
  1243. ``REQUEST``, because the former are more explicit. The property ``REQUEST`` is
  1244. deprecated and will be removed in Django 1.9.
  1245. ``django.utils.datastructures.MergeDict`` class
  1246. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1247. ``MergeDict`` exists primarily to support merging ``POST`` and ``GET``
  1248. arguments into a ``REQUEST`` property on ``WSGIRequest``. To merge
  1249. dictionaries, use ``dict.update()`` instead. The class ``MergeDict`` is
  1250. deprecated and will be removed in Django 1.9.
  1251. Language codes ``zh-cn``, ``zh-tw`` and ``fy-nl``
  1252. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1253. The currently used language codes for Simplified Chinese ``zh-cn``,
  1254. Traditional Chinese ``zh-tw`` and (Western) Frysian ``fy-nl`` are deprecated
  1255. and should be replaced by the language codes ``zh-hans``, ``zh-hant`` and
  1256. ``fy`` respectively. If you use these language codes, you should rename the
  1257. locale directories and update your settings to reflect these changes. The
  1258. deprecated language codes will be removed in Django 1.9.
  1259. ``django.utils.functional.memoize`` function
  1260. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1261. The function ``memoize`` is deprecated and should be replaced by the
  1262. ``functools.lru_cache`` decorator (available from Python 3.2 onwards).
  1263. Django ships a backport of this decorator for older Python versions and it's
  1264. available at ``django.utils.lru_cache.lru_cache``. The deprecated function will
  1265. be removed in Django 1.9.
  1266. Geo Sitemaps
  1267. ~~~~~~~~~~~~
  1268. Google has retired support for the Geo Sitemaps format. Hence Django support
  1269. for Geo Sitemaps is deprecated and will be removed in Django 1.8.
  1270. Passing callable arguments to queryset methods
  1271. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1272. Callable arguments for querysets were an undocumented feature that was
  1273. unreliable. It's been deprecated and will be removed in Django 1.9.
  1274. Callable arguments were evaluated when a queryset was constructed rather than
  1275. when it was evaluated, thus this feature didn't offer any benefit compared to
  1276. evaluating arguments before passing them to queryset and created confusion that
  1277. the arguments may have been evaluated at query time.
  1278. ``ADMIN_FOR`` setting
  1279. ~~~~~~~~~~~~~~~~~~~~~
  1280. The ``ADMIN_FOR`` feature, part of the admindocs, has been removed. You can
  1281. remove the setting from your configuration at your convenience.
  1282. ``SplitDateTimeWidget`` with ``DateTimeField``
  1283. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1284. ``SplitDateTimeWidget`` support in :class:`~django.forms.DateTimeField` is
  1285. deprecated, use ``SplitDateTimeWidget`` with
  1286. :class:`~django.forms.SplitDateTimeField` instead.
  1287. ``validate``
  1288. ~~~~~~~~~~~~
  1289. The ``validate`` management command is deprecated in favor of the
  1290. :djadmin:`check` command.
  1291. ``django.core.management.BaseCommand``
  1292. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1293. ``requires_model_validation`` is deprecated in favor of a new
  1294. ``requires_system_checks`` flag. If the latter flag is missing, then the
  1295. value of the former flag is used. Defining both ``requires_system_checks`` and
  1296. ``requires_model_validation`` results in an error.
  1297. The ``check()`` method has replaced the old ``validate()`` method.
  1298. ``ModelAdmin`` validators
  1299. ~~~~~~~~~~~~~~~~~~~~~~~~~
  1300. The ``ModelAdmin.validator_class`` and ``default_validator_class`` attributes
  1301. are deprecated in favor of the new ``checks_class`` attribute.
  1302. The ``ModelAdmin.validate()`` method is deprecated in favor of
  1303. ``ModelAdmin.check()``.
  1304. The ``django.contrib.admin.validation`` module is deprecated.
  1305. ``django.db.backends.DatabaseValidation.validate_field``
  1306. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1307. This method is deprecated in favor of a new ``check_field`` method.
  1308. The functionality required by ``check_field()`` is the same as that provided
  1309. by ``validate_field()``, but the output format is different. Third-party database
  1310. backends needing this functionality should provide an implementation of
  1311. ``check_field()``.
  1312. Loading ``ssi`` and ``url`` template tags from ``future`` library
  1313. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1314. Django 1.3 introduced ``{% load ssi from future %}`` and
  1315. ``{% load url from future %}`` syntax for forward compatibility of the
  1316. ``ssi`` and :ttag:`url` template tags. This syntax is now deprecated and
  1317. will be removed in Django 1.9. You can simply remove the
  1318. ``{% load ... from future %}`` tags.
  1319. ``django.utils.text.javascript_quote``
  1320. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1321. ``javascript_quote()`` was an undocumented function present in ``django.utils.text``.
  1322. It was used internally in the :ref:`javascript_catalog view <javascript_catalog-view>`
  1323. whose implementation was changed to make use of ``json.dumps()`` instead.
  1324. If you were relying on this function to provide safe output from untrusted
  1325. strings, you should use ``django.utils.html.escapejs`` or the
  1326. :tfilter:`escapejs` template filter.
  1327. If all you need is to generate valid JavaScript strings, you can simply use
  1328. ``json.dumps()``.
  1329. ``fix_ampersands`` utils method and template filter
  1330. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1331. The ``django.utils.html.fix_ampersands`` method and the ``fix_ampersands``
  1332. template filter are deprecated, as the escaping of ampersands is already taken care
  1333. of by Django's standard HTML escaping features. Combining this with ``fix_ampersands``
  1334. would either result in double escaping, or, if the output is assumed to be safe,
  1335. a risk of introducing XSS vulnerabilities. Along with ``fix_ampersands``,
  1336. ``django.utils.html.clean_html`` is deprecated, an undocumented function that calls
  1337. ``fix_ampersands``.
  1338. As this is an accelerated deprecation, ``fix_ampersands`` and ``clean_html``
  1339. will be removed in Django 1.8.
  1340. Reorganization of database test settings
  1341. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1342. All database settings with a ``TEST_`` prefix have been deprecated in favor of
  1343. entries in a :setting:`TEST <DATABASE-TEST>` dictionary in the database
  1344. settings. The old settings will be supported until Django 1.9. For backwards
  1345. compatibility with older versions of Django, you can define both versions of
  1346. the settings as long as they match.
  1347. FastCGI support
  1348. ~~~~~~~~~~~~~~~
  1349. FastCGI support via the ``runfcgi`` management command will be removed in
  1350. Django 1.9. Please deploy your project using WSGI.
  1351. Moved objects in ``contrib.sites``
  1352. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1353. Following the app-loading refactor, two objects in
  1354. ``django.contrib.sites.models`` needed to be moved because they must be
  1355. available without importing ``django.contrib.sites.models`` when
  1356. ``django.contrib.sites`` isn't installed. Import ``RequestSite`` from
  1357. ``django.contrib.sites.requests`` and ``get_current_site()`` from
  1358. ``django.contrib.sites.shortcuts``. The old import locations will work until
  1359. Django 1.9.
  1360. ``django.forms.forms.get_declared_fields()``
  1361. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1362. Django no longer uses this functional internally. Even though it's a private
  1363. API, it'll go through the normal deprecation cycle.
  1364. Private Query Lookup APIs
  1365. ~~~~~~~~~~~~~~~~~~~~~~~~~
  1366. Private APIs ``django.db.models.sql.where.WhereNode.make_atom()`` and
  1367. ``django.db.models.sql.where.Constraint`` are deprecated in favor of the new
  1368. :doc:`custom lookups API </ref/models/lookups>`.
  1369. .. removed-features-1.7:
  1370. Features removed in 1.7
  1371. =======================
  1372. These features have reached the end of their
  1373. :ref:`deprecation cycle <deprecation-removed-in-1.7>` and so have been
  1374. removed in Django 1.7 (please see the
  1375. :ref:`deprecation timeline <deprecation-removed-in-1.7>` for more details):
  1376. * ``django.utils.simplejson`` is removed.
  1377. * ``django.utils.itercompat.product`` is removed.
  1378. * INSTALLED_APPS and TEMPLATE_DIRS are no longer corrected from a plain
  1379. string into a tuple.
  1380. * :class:`~django.http.HttpResponse`,
  1381. :class:`~django.template.response.SimpleTemplateResponse`,
  1382. :class:`~django.template.response.TemplateResponse`,
  1383. :func:`~django.shortcuts.render_to_response`,
  1384. :func:`~django.contrib.sitemaps.views.index`, and
  1385. :func:`~django.contrib.sitemaps.views.sitemap` no longer take a ``mimetype``
  1386. argument
  1387. * :class:`~django.http.HttpResponse` immediately consumes its content if it's
  1388. an iterator.
  1389. * The ``AUTH_PROFILE_MODULE`` setting, and the ``get_profile()`` method on
  1390. the User model are removed.
  1391. * The ``cleanup`` management command is removed.
  1392. * The ``daily_cleanup.py`` script is removed.
  1393. * :meth:`~django.db.models.query.QuerySet.select_related` no longer has a
  1394. ``depth`` keyword argument.
  1395. * The ``get_warnings_state()``/``restore_warnings_state()``
  1396. functions from :mod:`django.test.utils` and the ``save_warnings_state()``/
  1397. ``restore_warnings_state()``
  1398. :ref:`django.test.*TestCase <django-testcase-subclasses>` are removed.
  1399. * The ``check_for_test_cookie`` method in
  1400. :class:`~django.contrib.auth.forms.AuthenticationForm` is removed.
  1401. * The version of :func:`django.contrib.auth.views.password_reset_confirm` that
  1402. supports base36 encoded user IDs
  1403. (``django.contrib.auth.views.password_reset_confirm_uidb36``) is removed.
  1404. * The ``django.utils.encoding.StrAndUnicode`` mix-in is removed.