1.7.txt 81 KB

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