1.7.txt 79 KB

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