1.7.txt 61 KB

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