========================Django 1.4 release notes========================*March 23, 2012*Welcome to Django 1.4!These release notes cover the :ref:`new features <whats-new-1.4>`, as well assome :ref:`backwards incompatible changes <backwards-incompatible-1.4>` you'llwant to be aware of when upgrading from Django 1.3 or older versions. We'vealso dropped some features, which are detailed in :ref:`our deprecation plan<deprecation-removed-in-1.4>`, and we've :ref:`begun the deprecation processfor some features <deprecated-features-1.4>`.Overview========The biggest new feature in Django 1.4 is `support for time zones`_ whenhandling date/times. When enabled, this Django will store date/times in UTC,use timezone-aware objects internally, and translate them to users' localtimezones for display.If you're upgrading an existing project to Django 1.4, switching to the timezoneaware mode may take some care: the new mode disallows some rather sloppybehavior that used to be accepted. We encourage anyone who's upgrading to checkout the :ref:`timezone migration guide <time-zones-migration-guide>` and the:ref:`timezone FAQ <time-zones-faq>` for useful pointers.Other notable new features in Django 1.4 include:* A number of ORM improvements, including `SELECT FOR UPDATE support`_,the ability to `bulk insert <#model-objects-bulk-create-in-the-orm>`_large datasets for improved performance, and`QuerySet.prefetch_related`_, a method to batch-load related objectsin areas where :meth:`~django.db.models.query.QuerySet.select_related`doesn't work.* Some nice security additions, including `improved password hashing`_(featuring PBKDF2_ and bcrypt_ support), new `tools for cryptographicsigning`_, several `CSRF improvements`_, and `simple clickjackingprotection`_.* An `updated default project layout and manage.py`_ that removes the "magic"from prior versions. And for those who don't like the new layout, you canuse `custom project and app templates`_ instead!* `Support for in-browser testing frameworks`_ (like Selenium_).* ... and a whole lot more; `see below <#what-s-new-in-django-1-4>`_!Wherever possible we try to introduce new features in a backwards-compatiblemanner per :doc:`our API stability policy </misc/api-stability>` policy.However, as with previous releases, Django 1.4 ships with some minor:ref:`backwards incompatible changes <backwards-incompatible-1.4>`; peopleupgrading from previous versions of Django should read that list carefully.Python compatibility====================Django 1.4 has dropped support for Python 2.4. Python 2.5 is now the minimumrequired Python version. Django is tested and supported on Python 2.5, 2.6 and2.7.This change should affect only a small number of Django users, as mostoperating-system vendors today are shipping Python 2.5 or newer as their defaultversion. If you're still using Python 2.4, however, you'll need to stick toDjango 1.3 until you can upgrade. Per :doc:`our support policy</internals/release-process>`, Django 1.3 will continue to receive securitysupport until the release of Django 1.5.Django does not support Python 3.x at this time. At some point before therelease of Django 1.4, we plan to publish a document outlining our fulltimeline for deprecating Python 2.x and moving to Python 3.x... _whats-new-1.4:What's new in Django 1.4========================Support for time zones----------------------In previous versions, Django used "naive" date/times (that is, date/timeswithout an associated time zone), leaving it up to each developer to interpretwhat a given date/time "really means". This can cause all sorts of subtletimezone-related bugs.In Django 1.4, you can now switch Django into a more correct, time-zone awaremode. In this mode, Django stores date and time information in UTC in thedatabase, uses time-zone-aware datetime objects internally and translates themto the end user's time zone in templates and forms. Reasons for using thisfeature include:- Customizing date and time display for users around the world.- Storing datetimes in UTC for database portability and interoperability.(This argument doesn't apply to PostgreSQL, because it already storestimestamps with time zone information in Django 1.3.)- Avoiding data corruption problems around DST transitions.Time zone support is enabled by default in new projects created with:djadmin:`startproject`. If you want to use this feature in an existingproject, read the :ref:`migration guide <time-zones-migration-guide>`. If youencounter problems, there's a helpful :ref:`FAQ <time-zones-faq>`.Support for in-browser testing frameworks-----------------------------------------Django 1.4 supports integration with in-browser testing frameworks likeSelenium_. The new :class:`django.test.LiveServerTestCase` base class lets youtest the interactions between your site's front and back ends morecomprehensively. See the:class:`documentation<django.test.LiveServerTestCase>` for more details andconcrete examples... _Selenium: https://www.selenium.dev/Updated default project layout and ``manage.py``------------------------------------------------Django 1.4 ships with an updated default project layout and ``manage.py`` filefor the :djadmin:`startproject` management command. These fix some issues withthe previous ``manage.py`` handling of Python import paths that caused doubleimports, trouble moving from development to deployment, and otherdifficult-to-debug path issues.The previous ``manage.py`` called functions that are now deprecated, and thusprojects upgrading to Django 1.4 should update their ``manage.py``. (Theold-style ``manage.py`` will continue to work as before until Django 1.6. In1.5 it will raise ``DeprecationWarning``).The new recommended ``manage.py`` file should look like this::#!/usr/bin/env pythonimport os, sysif __name__ == "__main__":os.environ.setdefault("DJANGO_SETTINGS_MODULE", "{{ project_name }}.settings")from django.core.management import execute_from_command_lineexecute_from_command_line(sys.argv)``{{ project_name }}`` should be replaced with the Python package name of theactual project.If settings, URLconfs and apps within the project are imported or referencedusing the project name prefix (e.g. ``myproject.settings``, ``ROOT_URLCONF ="myproject.urls"``, etc.), the new ``manage.py`` will need to be moved onedirectory up, so it is outside the project package rather than adjacent to``settings.py`` and ``urls.py``.For instance, with the following layout::manage.pymysite/__init__.pysettings.pyurls.pymyapp/__init__.pymodels.pyYou could import ``mysite.settings``, ``mysite.urls``, and ``mysite.myapp``,but not ``settings``, ``urls``, or ``myapp`` as top-level modules.Anything imported as a top-level module can be placed adjacent to the new``manage.py``. For instance, to decouple ``myapp`` from the project module andimport it as just ``myapp``, place it outside the ``mysite/`` directory::manage.pymyapp/__init__.pymodels.pymysite/__init__.pysettings.pyurls.pyIf the same code is imported inconsistently (some places with the projectprefix, some places without it), the imports will need to be cleaned up whenswitching to the new ``manage.py``.Custom project and app templates--------------------------------The :djadmin:`startapp` and :djadmin:`startproject` management commandsnow have a ``--template`` option for specifying a path or URL to a custom appor project template.For example, Django will use the ``/path/to/my_project_template`` directorywhen you run the following command::django-admin.py startproject --template=/path/to/my_project_template myprojectYou can also now provide a destination directory as the secondargument to both :djadmin:`startapp` and :djadmin:`startproject`::django-admin.py startapp myapp /path/to/new/appdjango-admin.py startproject myproject /path/to/new/projectFor more information, see the :djadmin:`startapp` and :djadmin:`startproject`documentation.Improved WSGI support---------------------The :djadmin:`startproject` management command now adds a :file:`wsgi.py`module to the initial project layout, containing a simple WSGI application thatcan be used for :doc:`deploying with WSGI appservers</howto/deployment/wsgi/index>`.The :djadmin:`built-in development server<runserver>` now supports using anexternally-defined WSGI callable, which makes it possible to run ``runserver``with the same WSGI configuration that is used for deployment. The new:setting:`WSGI_APPLICATION` setting lets you configure which WSGI callable:djadmin:`runserver` uses.(The ``runfcgi`` management command also internally wraps the WSGIcallable configured via :setting:`WSGI_APPLICATION`.)``SELECT FOR UPDATE`` support-----------------------------Django 1.4 includes a :meth:`QuerySet.select_for_update()<django.db.models.query.QuerySet.select_for_update>` method, which generates a``SELECT ... FOR UPDATE`` SQL query. This will lock rows until the end of thetransaction, meaning other transactions cannot modify or delete rows matched bya ``FOR UPDATE`` query.For more details, see the documentation for:meth:`~django.db.models.query.QuerySet.select_for_update`.``Model.objects.bulk_create`` in the ORM----------------------------------------This method lets you create multiple objects more efficiently. It can result insignificant performance increases if you have many objects.Django makes use of this internally, meaning some operations (such as databasesetup for test suites) have seen a performance benefit as a result.See the :meth:`~django.db.models.query.QuerySet.bulk_create` docs for moreinformation.``QuerySet.prefetch_related``-----------------------------Similar to :meth:`~django.db.models.query.QuerySet.select_related` but with adifferent strategy and broader scope,:meth:`~django.db.models.query.QuerySet.prefetch_related` has been added to:class:`~django.db.models.query.QuerySet`. This method returns a new``QuerySet`` that will prefetch each of the specified related lookups in asingle batch as soon as the query begins to be evaluated. Unlike``select_related``, it does the joins in Python, not in the database, andsupports many-to-many relationships, ``GenericForeignKey`` and more. Thisallows you to fix a very common performance problem in which your code ends updoing O(n) database queries (or worse) if objects on your primary ``QuerySet``each have many related objects that you also need to fetch.Improved password hashing-------------------------Django's auth system (``django.contrib.auth``) stores passwords using a one-wayalgorithm. Django 1.3 uses the SHA1_ algorithm, but increasing processor speedsand theoretical attacks have revealed that SHA1 isn't as secure as we'd like.Thus, Django 1.4 introduces a new password storage system: by default Django nowuses the PBKDF2_ algorithm (as recommended by NIST_). You can also easily choosea different algorithm (including the popular bcrypt_ algorithm). For moredetails, see :ref:`auth_password_storage`... _sha1: https://en.wikipedia.org/wiki/SHA1.. _pbkdf2: https://en.wikipedia.org/wiki/PBKDF2.. _nist: https://csrc.nist.gov/publications/detail/sp/800-132/final.. _bcrypt: https://en.wikipedia.org/wiki/BcryptHTML5 doctype-------------We've switched the admin and other bundled templates to use the HTML5doctype. While Django will be careful to maintain compatibility with olderbrowsers, this change means that you can use any HTML5 features you need inadmin pages without having to lose HTML validity or override the providedtemplates to change the doctype.List filters in admin interface-------------------------------Prior to Django 1.4, the :mod:`~django.contrib.admin` app let you specifychange list filters by specifying a field lookup, but it didn't allow you tocreate custom filters. This has been rectified with a simple API (previouslyused internally and known as "FilterSpec"). For more details, see thedocumentation for :attr:`~django.contrib.admin.ModelAdmin.list_filter`.Multiple sort in admin interface--------------------------------The admin change list now supports sorting on multiple columns. It respects allelements of the :attr:`~django.contrib.admin.ModelAdmin.ordering` attribute, andsorting on multiple columns by clicking on headers is designed to mimic thebehavior of desktop GUIs. We also added a:meth:`~django.contrib.admin.ModelAdmin.get_ordering` method for specifying theordering dynamically (i.e., depending on the request).New ``ModelAdmin`` methods--------------------------We added a :meth:`~django.contrib.admin.ModelAdmin.save_related` method to:mod:`~django.contrib.admin.ModelAdmin` to ease customization of howrelated objects are saved in the admin.Two other new :class:`~django.contrib.admin.ModelAdmin` methods,:meth:`~django.contrib.admin.ModelAdmin.get_list_display` and:meth:`~django.contrib.admin.ModelAdmin.get_list_display_links`enable dynamic customization of fields and links displayed on the adminchange list.Admin inlines respect user permissions--------------------------------------Admin inlines now only allow those actions for which the user haspermission. For ``ManyToMany`` relationships with an auto-created intermediatemodel (which does not have its own permissions), the change permission for therelated model determines if the user has the permission to add, change ordelete relationships.Tools for cryptographic signing-------------------------------Django 1.4 adds both a low-level API for signing values and a high-level APIfor setting and reading signed cookies, one of the most common uses ofsigning in web applications.See the :doc:`cryptographic signing </topics/signing>` docs for moreinformation.Cookie-based session backend----------------------------Django 1.4 introduces a cookie-based session backend that uses the tools for:doc:`cryptographic signing </topics/signing>` to store the session data inthe client's browser... warning::Session data is signed and validated by the server, but it's notencrypted. This means a user can view any data stored in thesession but cannot change it. Please read the documentation forfurther clarification before using this backend.See the :ref:`cookie-based session backend <cookie-session-backend>` docs formore information.New form wizard---------------The previous ``FormWizard`` from ``django.contrib.formtools`` has beenreplaced with a new implementation based on the class-based viewsintroduced in Django 1.3. It features a pluggable storage API and doesn'trequire the wizard to pass around hidden fields for every previous step.Django 1.4 ships with a session-based storage backend and a cookie-basedstorage backend. The latter uses the tools for:doc:`cryptographic signing </topics/signing>` also introduced inDjango 1.4 to store the wizard's state in the user's cookies.``reverse_lazy``----------------A lazily evaluated version of ``reverse()`` was added to allow using URLreversals before the project's URLconf gets loaded.Translating URL patterns------------------------Django can now look for a language prefix in the URLpattern when using the new:func:`~django.conf.urls.i18n.i18n_patterns` helper function.It's also now possible to define translatable URL patterns using``django.utils.translation.ugettext_lazy()``. See:ref:`url-internationalization` for more information about the language prefixand how to internationalize URL patterns.Contextual translation support for ``{% trans %}`` and ``{% blocktrans %}``---------------------------------------------------------------------------The :ref:`contextual translation<contextual-markers>` support introduced inDjango 1.3 via the ``pgettext`` function has been extended to the:ttag:`trans` and :ttag:`blocktrans` template tags using the new ``context``keyword.Customizable ``SingleObjectMixin`` URLConf kwargs-------------------------------------------------Two new attributes,:attr:`pk_url_kwarg<django.views.generic.detail.SingleObjectMixin.pk_url_kwarg>`and:attr:`slug_url_kwarg<django.views.generic.detail.SingleObjectMixin.slug_url_kwarg>`,have been added to :class:`~django.views.generic.detail.SingleObjectMixin` toenable the customization of URLconf keyword arguments used for singleobject generic views.Assignment template tags------------------------A new ``assignment_tag`` helper function was added to ``template.Library`` toease the creation of template tags that store data in a specified contextvariable.``*args`` and ``**kwargs`` support for template tag helper functions--------------------------------------------------------------------The :ref:`simple_tag<howto-custom-template-tags-simple-tags>`,:ref:`inclusion_tag <howto-custom-template-tags-inclusion-tags>` and newlyintroduced ``assignment_tag`` template helper functions may now accept anynumber of positional or keyword arguments. For example::@register.simple_tagdef my_tag(a, b, *args, **kwargs):warning = kwargs['warning']profile = kwargs['profile']...return ...Then, in the template, any number of arguments may be passed to the template tag.For example:.. code-block:: html+django{% my_tag 123 "abcd" book.title warning=message|lower profile=user.profile %}No wrapping of exceptions in ``TEMPLATE_DEBUG`` mode----------------------------------------------------In previous versions of Django, whenever the ``TEMPLATE_DEBUG`` settingwas ``True``, any exception raised during template rendering (even exceptionsunrelated to template syntax) were wrapped in ``TemplateSyntaxError`` andre-raised. This was done in order to provide detailed template source locationinformation in the debug 500 page.In Django 1.4, exceptions are no longer wrapped. Instead, the originalexception is annotated with the source information. This means that catchingexceptions from template rendering is now consistent regardless of the value of``TEMPLATE_DEBUG``, and there's no need to catch and unwrap``TemplateSyntaxError`` in order to catch other errors.``truncatechars`` template filter---------------------------------This new filter truncates a string to be no longer than the specifiednumber of characters. Truncated strings end with a translatable ellipsissequence ("..."). See the documentation for :tfilter:`truncatechars` formore details.``static`` template tag-----------------------The :mod:`staticfiles<django.contrib.staticfiles>` contrib app has a new``static`` template tag to refer to files saved with the:setting:`STATICFILES_STORAGE` storage backend. It uses the storage backend's``url`` method and therefore supports advanced features such as :ref:`servingfiles from a cloud service<staticfiles-from-cdn>`.``CachedStaticFilesStorage`` storage backend--------------------------------------------The :mod:`staticfiles<django.contrib.staticfiles>` contrib app now has a``django.contrib.staticfiles.storage.CachedStaticFilesStorage`` backendthat caches the files it saves (when running the :djadmin:`collectstatic`management command) by appending the MD5 hash of the file's content to thefilename. For example, the file ``css/styles.css`` would also be saved as``css/styles.55e7cbb9ba48.css``Simple clickjacking protection------------------------------We've added a middleware to provide easy protection against `clickjacking<https://en.wikipedia.org/wiki/Clickjacking>`_ using the ``X-Frame-Options``header. It's not enabled by default for backwards compatibility reasons, butyou'll almost certainly want to :doc:`enable it </ref/clickjacking/>` to helpplug that security hole for browsers that support the header.CSRF improvements-----------------We've made various improvements to our CSRF features, including the:func:`~django.views.decorators.csrf.ensure_csrf_cookie` decorator, which canhelp with AJAX-heavy sites; protection for PUT and DELETE requests; and the:setting:`CSRF_COOKIE_SECURE` and :setting:`CSRF_COOKIE_PATH` settings, which canimprove the security and usefulness of CSRF protection. See the :doc:`CSRFdocs </ref/csrf>` for more information.Error report filtering----------------------We added two function decorators,:func:`~django.views.decorators.debug.sensitive_variables` and:func:`~django.views.decorators.debug.sensitive_post_parameters`, to allowdesignating the local variables and POST parameters that may contain sensitiveinformation and should be filtered out of error reports.All POST parameters are now systematically filtered out of error reports forcertain views (``login``, ``password_reset_confirm``, ``password_change`` and``add_view`` in :mod:`django.contrib.auth.views`, as well as``user_change_password`` in the admin app) to prevent the leaking of sensitiveinformation such as user passwords.You can override or customize the default filtering by writing a :ref:`customfilter<custom-error-reports>`. For more information see the docs on:ref:`Filtering error reports<filtering-error-reports>`.Extended IPv6 support---------------------Django 1.4 can now better handle IPv6 addresses with the new:class:`~django.db.models.GenericIPAddressField` model field,:class:`~django.forms.GenericIPAddressField` form field andthe validators :data:`~django.core.validators.validate_ipv46_address` and:data:`~django.core.validators.validate_ipv6_address`.HTML comparisons in tests-------------------------The base classes in :mod:`django.test` now have some helpers tocompare HTML without tripping over irrelevant differences in whitespace,argument quoting/ordering and closing of self-closing tags. You can eithercompare HTML directly with the new:meth:`~django.test.SimpleTestCase.assertHTMLEqual` and:meth:`~django.test.SimpleTestCase.assertHTMLNotEqual` assertions, or usethe ``html=True`` flag with:meth:`~django.test.SimpleTestCase.assertContains` and:meth:`~django.test.SimpleTestCase.assertNotContains` to test whether theclient's response contains a given HTML fragment. See the :ref:`assertionsdocumentation <assertions>` for more.Two new date format strings---------------------------Two new :tfilter:`date` formats were added for use in template filters,template tags and :doc:`/topics/i18n/formatting`:- ``e`` -- the name of the timezone of the given datetime object- ``o`` -- the ISO 8601 year numberPlease make sure to update your :ref:`custom format files<custom-format-files>` if they contain either ``e`` or ``o`` in a formatstring. For example a Spanish localization format previously only escaped the``d`` format character::DATE_FORMAT = r'j \de F \de Y'But now it needs to also escape ``e`` and ``o``::DATE_FORMAT = r'j \d\e F \d\e Y'For more information, see the :tfilter:`date` documentation.Minor features--------------Django 1.4 also includes several smaller improvements worth noting:* A more usable stacktrace in the technical 500 page. Frames in thestack trace that reference Django's framework code are dimmed out,while frames in application code are slightly emphasized. This changemakes it easier to scan a stacktrace for issues in application code.* :doc:`Tablespace support </topics/db/tablespaces>` in PostgreSQL.* Customizable names for :meth:`~django.template.Library.simple_tag`.* In the documentation, a helpful :doc:`security overview </topics/security>`page.* The ``django.contrib.auth.models.check_password`` function has been movedto the :mod:`django.contrib.auth.hashers` module. Importing it from the oldlocation will still work, but you should update your imports.* The :djadmin:`collectstatic` management command now has a ``--clear`` optionto delete all files at the destination before copying or linking the staticfiles.* It's now possible to load fixtures containing forward references when usingMySQL with the InnoDB database engine.* A new 403 response handler has been added as``'django.views.defaults.permission_denied'``. You can set your own handler bysetting the value of :data:`django.conf.urls.handler403`. See thedocumentation about :ref:`the 403 (HTTP Forbidden) view<http_forbidden_view>`for more information.* The :djadmin:`makemessages` command uses a new and more accurate lexer,`JsLex`_, for extracting translatable strings from JavaScript files... _JsLex: https://pypi.org/project/jslex/* The :ttag:`trans` template tag now takes an optional ``as`` argument tobe able to retrieve a translation string without displaying it but settinga template context variable instead.* The :ttag:`if` template tag now supports ``{% elif %}`` clauses.* If your Django app is behind a proxy, you might find the new:setting:`SECURE_PROXY_SSL_HEADER` setting useful. It solves the problem of yourproxy "eating" the fact that a request came in via HTTPS. But only use thissetting if you know what you're doing.* A new, plain-text, version of the HTTP 500 status code internal error pageserved when :setting:`DEBUG` is ``True`` is now sent to the client whenDjango detects that the request has originated in JavaScript code.(``is_ajax()`` is used for this.)Like its HTML counterpart, it contains a collection of differentpieces of information about the state of the application.This should make it easier to read when debugging interaction withclient-side JavaScript.* Added the :option:`makemessages --no-location` option.* Changed the ``locmem`` cache backend to use``pickle.HIGHEST_PROTOCOL`` for better compatibility with the othercache backends.* Added support in the ORM for generating ``SELECT`` queries containing``DISTINCT ON``.The ``distinct()`` ``QuerySet`` method now accepts an optional list of modelfield names. If specified, then the ``DISTINCT`` statement is limited to thesefields. This is only supported in PostgreSQL.For more details, see the documentation for:meth:`~django.db.models.query.QuerySet.distinct`.* The admin login page will add a password reset link if you include a URL withthe name ``'admin_password_reset'`` in your ``urls.py``, so plugging in thebuilt-in password reset mechanism and making it available is now much easier.For details, see :ref:`auth_password_reset`.* The MySQL database backend can now make use of the savepoint featureimplemented by MySQL version 5.0.3 or newer with the InnoDB storage engine.* It's now possible to pass initial values to the model forms that are part ofboth model formsets and inline model formsets as returned from factoryfunctions ``modelformset_factory`` and ``inlineformset_factory`` respectivelyjust like with regular formsets. However, initial values only apply to extraforms, i.e. those which are not bound to an existing model instance.* The sitemaps framework can now handle HTTPS links using the new:attr:`Sitemap.protocol <django.contrib.sitemaps.Sitemap.protocol>` classattribute.* A new :class:`django.test.SimpleTestCase` subclass of:class:`unittest.TestCase`that's lighter than :class:`django.test.TestCase` and company. It can beuseful in tests that don't need to hit a database. See:ref:`testcase_hierarchy_diagram`... _backwards-incompatible-1.4:Backwards incompatible changes in 1.4=====================================SECRET_KEY setting is required------------------------------Running Django with an empty or known :setting:`SECRET_KEY` disables many ofDjango's security protections and can lead to remote-code-executionvulnerabilities. No Django site should ever be run without a:setting:`SECRET_KEY`.In Django 1.4, starting Django with an empty :setting:`SECRET_KEY` will raise a``DeprecationWarning``. In Django 1.5, it will raise an exception and Djangowill refuse to start. This is slightly accelerated from the usual deprecationpath due to the severity of the consequences of running Django with no:setting:`SECRET_KEY`.``django.contrib.admin``------------------------The included administration app ``django.contrib.admin`` has for a long timeshipped with a default set of static files such as JavaScript, images andstylesheets. Django 1.3 added a new contrib app ``django.contrib.staticfiles``to handle such files in a generic way and defined conventions for staticfiles included in apps.Starting in Django 1.4, the admin's static files also follow thisconvention, to make the files easier to deploy. In previous versions of Django,it was also common to define an ``ADMIN_MEDIA_PREFIX`` setting to point to theURL where the admin's static files live on a web server. This setting has nowbeen deprecated and replaced by the more general setting :setting:`STATIC_URL`.Django will now expect to find the admin static files under the URL``<STATIC_URL>/admin/``.If you've previously used a URL path for ``ADMIN_MEDIA_PREFIX`` (e.g.``/media/``) simply make sure :setting:`STATIC_URL` and :setting:`STATIC_ROOT`are configured and your web server serves those files correctly. Thedevelopment server continues to serve the admin files just like before. Readthe :doc:`static files howto </howto/static-files/index>` for more details.If your ``ADMIN_MEDIA_PREFIX`` is set to a specific domain (e.g.``http://media.example.com/admin/``), make sure to also set your:setting:`STATIC_URL` setting to the correct URL -- for example,``http://media.example.com/``... warning::If you're implicitly relying on the path of the admin static files withinDjango's source code, you'll need to update that path. The files were movedfrom :file:`django/contrib/admin/media/` to:file:`django/contrib/admin/static/admin/`.Supported browsers for the admin--------------------------------Django hasn't had a clear policy on which browsers are supported by theadmin app. Our new policy formalizes existing practices: `YUI's A-grade`_browsers should provide a fully-functional admin experience, with the notableexception of Internet Explorer 6, which is no longer supported.Released over 10 years ago, IE6 imposes many limitations on modern webdevelopment. The practical implications of this policy are that contributorsare free to improve the admin without consideration for these limitations.This new policy **has no impact** on sites you develop using Django. It onlyapplies to the Django admin. Feel free to develop apps compatible with anyrange of browsers... _YUI's A-grade: https://github.com/yui/yui3/wiki/Graded-Browser-SupportRemoved admin icons-------------------As part of an effort to improve the performance and usability of the admin'schange-list sorting interface and :attr:`horizontal<django.contrib.admin.ModelAdmin.filter_horizontal>` and :attr:`vertical<django.contrib.admin.ModelAdmin.filter_vertical>` "filter" widgets, some iconfiles were removed and grouped into two sprite files.Specifically: ``selector-add.gif``, ``selector-addall.gif``,``selector-remove.gif``, ``selector-removeall.gif``,``selector_stacked-add.gif`` and ``selector_stacked-remove.gif`` werecombined into ``selector-icons.gif``; and ``arrow-up.gif`` and``arrow-down.gif`` were combined into ``sorting-icons.gif``.If you used those icons to customize the admin, then you'll need to replacethem with your own icons or get the files from a previous release.CSS class names in admin forms------------------------------To avoid conflicts with other common CSS class names (e.g. "button"), we addeda prefix ("field-") to all CSS class names automatically generated from theform field names in the main admin forms, stacked inline forms and tabularinline cells. You'll need to take that prefix into account in your customstyle sheets or JavaScript files if you previously used plain field names asselectors for custom styles or JavaScript transformations.Compatibility with old signed data----------------------------------Django 1.3 changed the cryptographic signing mechanisms used in a number ofplaces in Django. While Django 1.3 kept fallbacks that would accept hashesproduced by the previous methods, these fallbacks are removed in Django 1.4.So, if you upgrade to Django 1.4 directly from 1.2 or earlier, you maylose/invalidate certain pieces of data that have been cryptographically signedusing an old method. To avoid this, use Django 1.3 first for a period of timeto allow the signed data to expire naturally. The affected parts are detailedbelow, with 1) the consequences of ignoring this advice and 2) the amount oftime you need to run Django 1.3 for the data to expire or become irrelevant.* ``contrib.sessions`` data integrity check* Consequences: The user will be logged out, and session data will be lost.* Time period: Defined by :setting:`SESSION_COOKIE_AGE`.* ``contrib.auth`` password reset hash* Consequences: Password reset links from before the upgrade will not work.* Time period: Defined by ``PASSWORD_RESET_TIMEOUT_DAYS``.Form-related hashes: these have a much shorter lifetime and are relevantonly for the short window where a user might fill in a form generated by thepre-upgrade Django instance and try to submit it to the upgraded Djangoinstance:* ``contrib.comments`` form security hash* Consequences: The user will see the validation error "Security hash failed."* Time period: The amount of time you expect users to take filling out commentforms.* ``FormWizard`` security hash* Consequences: The user will see an error about the form having expiredand will be sent back to the first page of the wizard, losing the dataentered so far.* Time period: The amount of time you expect users to take filling out theaffected forms.* CSRF check* Note: This is actually a Django 1.1 fallback, not Django 1.2,and it applies only if you're upgrading from 1.1.* Consequences: The user will see a 403 error with any CSRF-protected POSTform.* Time period: The amount of time you expect user to take filling outsuch forms.* ``contrib.auth`` user password hash-upgrade sequence* Consequences: Each user's password will be updated to a stronger passwordhash when it's written to the database in 1.4. This means that if youupgrade to 1.4 and then need to downgrade to 1.3, version 1.3 won't be ableto read the updated passwords.* Remedy: Set :setting:`PASSWORD_HASHERS` to use your original passwordhashing when you initially upgrade to 1.4. After you confirm your app workswell with Django 1.4 and you won't have to roll back to 1.3, enable the newpassword hashes.``django.contrib.flatpages``----------------------------Starting in 1.4, the:class:`~django.contrib.flatpages.middleware.FlatpageFallbackMiddleware` onlyadds a trailing slash and redirects if the resulting URL refers to an existingflatpage. For example, requesting ``/notaflatpageoravalidurl`` in a previousversion would redirect to ``/notaflatpageoravalidurl/``, which wouldsubsequently raise a 404. Requesting ``/notaflatpageoravalidurl`` now willimmediately raise a 404.Also, redirects returned by flatpages are now permanent (with 301 status code),to match the behavior of :class:`~django.middleware.common.CommonMiddleware`.Serialization of :class:`~datetime.datetime` and :class:`~datetime.time`------------------------------------------------------------------------As a consequence of time-zone support, and according to the ECMA-262specification, we made changes to the JSON serializer:* It includes the time zone for aware datetime objects. It raises an exceptionfor aware time objects.* It includes milliseconds for datetime and time objects. There is stillsome precision loss, because Python stores microseconds (6 digits) and JSONonly supports milliseconds (3 digits). However, it's better than discardingmicroseconds entirely.We changed the XML serializer to use the ISO8601 format for datetimes.The letter ``T`` is used to separate the date part from the time part, insteadof a space. Time zone information is included in the ``[+-]HH:MM`` format.Though the serializers now use these new formats when creating fixtures, theycan still load fixtures that use the old format.``supports_timezone`` changed to ``False`` for SQLite-----------------------------------------------------The database feature ``supports_timezone`` used to be ``True`` for SQLite.Indeed, if you saved an aware datetime object, SQLite stored a string thatincluded an UTC offset. However, this offset was ignored when loading the valueback from the database, which could corrupt the data.In the context of time-zone support, this flag was changed to ``False``, anddatetimes are now stored without time-zone information in SQLite. When:setting:`USE_TZ` is ``False``, if you attempt to save an aware datetimeobject, Django raises an exception.``MySQLdb``-specific exceptions-------------------------------The MySQL backend historically has raised ``MySQLdb.OperationalError``when a query triggered an exception. We've fixed this bug, and we now raise:exc:`django.db.DatabaseError` instead. If you were testing for``MySQLdb.OperationalError``, you'll need to update your ``except``clauses.Database connection's thread-locality-------------------------------------``DatabaseWrapper`` objects (i.e. the connection objects referenced by``django.db.connection`` and ``django.db.connections["some_alias"]``) used tobe thread-local. They are now global objects in order to be potentially sharedbetween multiple threads. While the individual connection objects are nowglobal, the ``django.db.connections`` dictionary referencing those objects isstill thread-local. Therefore if you just use the ORM or``DatabaseWrapper.cursor()`` then the behavior is still the same as before.Note, however, that ``django.db.connection`` does not directly reference thedefault ``DatabaseWrapper`` object anymore and is now a proxy to access thatobject's attributes. If you need to access the actual ``DatabaseWrapper``object, use ``django.db.connections[DEFAULT_DB_ALIAS]`` instead.As part of this change, all underlying SQLite connections are now enabled forpotential thread-sharing (by passing the ``check_same_thread=False`` attributeto pysqlite). ``DatabaseWrapper`` however preserves the previous behavior bydisabling thread-sharing by default, so this does not affect any existingcode that purely relies on the ORM or on ``DatabaseWrapper.cursor()``.Finally, while it's now possible to pass connections between threads, Djangodoesn't make any effort to synchronize access to the underlying backend.Concurrency behavior is defined by the underlying backend implementation.Check their documentation for details.``COMMENTS_BANNED_USERS_GROUP`` setting---------------------------------------Django's comments has historicallysupported excluding the comments of a special user group, but we've neverdocumented the feature properly and didn't enforce the exclusion in other partsof the app such as the template tags. To fix this problem, we removed the codefrom the feed class.If you rely on the feature and want to restore the old behavior, use a customcomment model manager to exclude the user group, like this::from django.conf import settingsfrom django.contrib.comments.managers import CommentManagerclass BanningCommentManager(CommentManager):def get_query_set(self):qs = super().get_query_set()if getattr(settings, 'COMMENTS_BANNED_USERS_GROUP', None):where = ['user_id NOT IN (SELECT user_id FROM auth_user_groups WHERE group_id = %s)']params = [settings.COMMENTS_BANNED_USERS_GROUP]qs = qs.extra(where=where, params=params)return qsSave this model manager in your custom comment app (e.g., in``my_comments_app/managers.py``) and add it your custom comment app model::from django.db import modelsfrom django.contrib.comments.models import Commentfrom my_comments_app.managers import BanningCommentManagerclass CommentWithTitle(Comment):title = models.CharField(max_length=300)objects = BanningCommentManager()``IGNORABLE_404_STARTS`` and ``IGNORABLE_404_ENDS`` settings------------------------------------------------------------Until Django 1.3, it was possible to exclude some URLs from Django's:doc:`404 error reporting</howto/error-reporting>` by adding prefixes to``IGNORABLE_404_STARTS`` and suffixes to ``IGNORABLE_404_ENDS``.In Django 1.4, these two settings are superseded by:setting:`IGNORABLE_404_URLS`, which is a list of compiled regularexpressions. Django won't send an email for 404 errors on URLs that match anyof them.Furthermore, the previous settings had some rather arbitrary default values::IGNORABLE_404_STARTS = ('/cgi-bin/', '/_vti_bin', '/_vti_inf')IGNORABLE_404_ENDS = ('mail.pl', 'mailform.pl', 'mail.cgi', 'mailform.cgi','favicon.ico', '.php')It's not Django's role to decide if your website has a legacy ``/cgi-bin/``section or a ``favicon.ico``. As a consequence, the default values of:setting:`IGNORABLE_404_URLS`, ``IGNORABLE_404_STARTS``, and``IGNORABLE_404_ENDS`` are all now empty.If you have customized ``IGNORABLE_404_STARTS`` or ``IGNORABLE_404_ENDS``, orif you want to keep the old default value, you should add the following linesin your settings file::import reIGNORABLE_404_URLS = (# for each <prefix> in IGNORABLE_404_STARTSre.compile(r'^<prefix>'),# for each <suffix> in IGNORABLE_404_ENDSre.compile(r'<suffix>$'),)Don't forget to escape characters that have a special meaning in a regularexpression, such as periods.CSRF protection extended to PUT and DELETE------------------------------------------Previously, Django's :doc:`CSRF protection </ref/csrf/>` providedprotection only against POST requests. Since use of PUT and DELETE methods inAJAX applications is becoming more common, we now protect all methods notdefined as safe by :rfc:`2616` -- i.e., we exempt GET, HEAD, OPTIONS and TRACE,and we enforce protection on everything else.If you're using PUT or DELETE methods in AJAX applications, please see the:ref:`instructions about using AJAX and CSRF <csrf-ajax>`.Password reset view now accepts ``subject_template_name``---------------------------------------------------------The ``password_reset`` view in ``django.contrib.auth`` now accepts a``subject_template_name`` parameter, which is passed to the password save formas a keyword argument. If you are using this view with a custom password resetform, then you will need to ensure your form's ``save()`` method accepts thiskeyword argument.``django.core.template_loaders``--------------------------------This was an alias to ``django.template.loader`` since 2005, and we've removed itwithout emitting a warning due to the length of the deprecation. If your codestill referenced this, please use ``django.template.loader`` instead.``django.db.models.fields.URLField.verify_exists``--------------------------------------------------This functionality has been removed due to intractable performance andsecurity issues. Any existing usage of ``verify_exists`` should beremoved.``django.core.files.storage.Storage.open``------------------------------------------The ``open`` method of the base Storage class used to take an obscure parameter``mixin`` that allowed you to dynamically change the base classes of thereturned file object. This has been removed. In the rare case you relied on the``mixin`` parameter, you can easily achieve the same by overriding the ``open``method, like this::from django.core.files import Filefrom django.core.files.storage import FileSystemStorageclass Spam(File):"""Spam, spam, spam, spam and spam."""def ham(self):return 'eggs'class SpamStorage(FileSystemStorage):"""A custom file storage backend."""def open(self, name, mode='rb'):return Spam(open(self.path(name), mode))YAML deserializer now uses ``yaml.safe_load``---------------------------------------------``yaml.load`` is able to construct any Python object, which may triggerarbitrary code execution if you process a YAML document that comes from anuntrusted source. This feature isn't necessary for Django's YAML deserializer,whose primary use is to load fixtures consisting of simple objects. Even thoughfixtures are trusted data, the YAML deserializer now uses ``yaml.safe_load``for additional security.Session cookies now have the ``httponly`` flag by default---------------------------------------------------------Session cookies now include the ``httponly`` attribute by default tohelp reduce the impact of potential XSS attacks. As a consequence ofthis change, session cookie data, including ``sessionid``, is no longeraccessible from JavaScript in many browsers. For strict backwardscompatibility, use ``SESSION_COOKIE_HTTPONLY = False`` in yoursettings file.The :tfilter:`urlize` filter no longer escapes every URL--------------------------------------------------------When a URL contains a ``%xx`` sequence, where ``xx`` are two hexadecimaldigits, :tfilter:`urlize` now assumes that the URL is already escaped anddoesn't apply URL escaping again. This is wrong for URLs whose unquoted formcontains a ``%xx`` sequence, but such URLs are very unlikely to happen in thewild, because they would confuse browsers too.``assertTemplateUsed`` and ``assertTemplateNotUsed`` as context manager-----------------------------------------------------------------------It's now possible to check whether a template was used within a block ofcode with :meth:`~django.test.SimpleTestCase.assertTemplateUsed` and:meth:`~django.test.SimpleTestCase.assertTemplateNotUsed`. And theycan be used as a context manager::with self.assertTemplateUsed('index.html'):render_to_string('index.html')with self.assertTemplateNotUsed('base.html'):render_to_string('index.html')See the :ref:`assertion documentation<assertions>` for more.Database connections after running the test suite-------------------------------------------------The default test runner no longer restores the database connections aftertests' execution. This prevents the production database from being exposed topotential threads that would still be running and attempting to create newconnections.If your code relied on connections to the production database being createdafter tests' execution, then you can restore the previous behavior bysubclassing ``DjangoTestRunner`` and overriding its ``teardown_databases()``method.Output of :djadmin:`manage.py help <help>`------------------------------------------:djadmin:`manage.py help <help>` now groups available commands by application.If you depended on the output of this command -- if you parsed it, for example-- then you'll need to update your code. To get a list of all availablemanagement commands in a script, use:djadmin:`manage.py help --commands <help>` instead.``extends`` template tag------------------------Previously, the :ttag:`extends` tag used a buggy method of parsing arguments,which could lead to it erroneously considering an argument as a string literalwhen it wasn't. It now uses ``parser.compile_filter``, like other tags.The internals of the tag aren't part of the official stable API, but in theinterests of full disclosure, the ``ExtendsNode.__init__`` definition haschanged, which may break any custom tags that use this class.Loading some incomplete fixtures no longer works------------------------------------------------Prior to 1.4, a default value was inserted for fixture objects that were missinga specific date or datetime value when auto_now or auto_now_add was set for thefield. This was something that should not have worked, and in 1.4 loading suchincomplete fixtures will fail. Because fixtures are a raw import, they shouldexplicitly specify all field values, regardless of field options on the model.Development Server Multithreading---------------------------------The development server is now is multithreaded by default. Use the:option:`runserver --nothreading` option to disable the use of threading in thedevelopment server::django-admin.py runserver --nothreadingAttributes disabled in markdown when safe mode set--------------------------------------------------Prior to Django 1.4, attributes were included in any markdown output regardlessof safe mode setting of the filter. With version > 2.1 of the Python-Markdownlibrary, an enable_attributes option was added. When the safe argument ispassed to the markdown filter, both the ``safe_mode=True`` and``enable_attributes=False`` options are set. If using a version of thePython-Markdown library less than 2.1, a warning is issued that the output isinsecure.FormMixin get_initial returns an instance-specific dictionary-------------------------------------------------------------In Django 1.3, the ``get_initial`` method of the:class:`django.views.generic.edit.FormMixin` class was returning theclass ``initial`` dictionary. This has been fixed to return a copy of thisdictionary, so form instances can modify their initial data without messingwith the class variable... _deprecated-features-1.4:Features deprecated in 1.4==========================Old styles of calling ``cache_page`` decorator----------------------------------------------Some legacy ways of calling :func:`~django.views.decorators.cache.cache_page`have been deprecated. Please see the documentation for the correct way to usethis decorator.Support for PostgreSQL versions older than 8.2----------------------------------------------Django 1.3 dropped support for PostgreSQL versions older than 8.0, and wesuggested using a more recent version because of performance improvementsand, more importantly, the end of upstream support periods for 8.0 and 8.1was near (November 2010).Django 1.4 takes that policy further and sets 8.2 as the minimum PostgreSQLversion it officially supports.Request exceptions are now always logged----------------------------------------When we added :doc:`logging support </topics/logging/>` in Django in 1.3, theadmin error email support was moved into the:class:`django.utils.log.AdminEmailHandler`, attached to the``'django.request'`` logger. In order to maintain the established behavior oferror emails, the ``'django.request'`` logger was called only when:setting:`DEBUG` was ``False``.To increase the flexibility of error logging for requests, the``'django.request'`` logger is now called regardless of the value of:setting:`DEBUG`, and the default settings file for new projects now includes aseparate filter attached to :class:`django.utils.log.AdminEmailHandler` toprevent admin error emails in ``DEBUG`` mode::'filters': {'require_debug_false': {'()': 'django.utils.log.RequireDebugFalse'}},'handlers': {'mail_admins': {'level': 'ERROR','filters': ['require_debug_false'],'class': 'django.utils.log.AdminEmailHandler'}},If your project was created prior to this change, your :setting:`LOGGING`setting will not include this new filter. In order to maintainbackwards-compatibility, Django will detect that your ``'mail_admins'`` handlerconfiguration includes no ``'filters'`` section and will automatically addthis filter for you and issue a pending-deprecation warning. This will become adeprecation warning in Django 1.5, and in Django 1.6 thebackwards-compatibility shim will be removed entirely.The existence of any ``'filters'`` key under the ``'mail_admins'`` handler willdisable this backward-compatibility shim and deprecation warning.``django.conf.urls.defaults``-----------------------------Until Django 1.3, the ``include()``, ``patterns()``, and ``url()`` functions,plus :data:`~django.conf.urls.handler404` and :data:`~django.conf.urls.handler500`were located in a ``django.conf.urls.defaults`` module.In Django 1.4, they live in :mod:`django.conf.urls`.``django.contrib.databrowse``-----------------------------Databrowse has not seen active development for some time, and this does not showany sign of changing. There had been a suggestion for a `GSOC project`_ tointegrate the functionality of databrowse into the admin, but no progress wasmade. While Databrowse has been deprecated, an enhancement of``django.contrib.admin`` providing a similar feature set is still possible... _GSOC project: https://code.djangoproject.com/wiki/SummerOfCode2011#IntegratedatabrowseintotheadminThe code that powers Databrowse is licensed under the same terms as Djangoitself, so it's available to be adopted by an individual or group asa third-party project.``django.core.management.setup_environ``----------------------------------------This function temporarily modified ``sys.path`` in order to make the parent"project" directory importable under the old flat :djadmin:`startproject`layout. This function is now deprecated, as its path workarounds are no longerneeded with the new ``manage.py`` and default project layout.This function was never documented or part of the public API, but it was widelyrecommended for use in setting up a "Django environment" for a user script.These uses should be replaced by setting the :envvar:`DJANGO_SETTINGS_MODULE`environment variable or using :func:`django.conf.settings.configure`.``django.core.management.execute_manager``------------------------------------------This function was previously used by ``manage.py`` to execute a managementcommand. It is identical to``django.core.management.execute_from_command_line``, except that it firstcalls ``setup_environ``, which is now deprecated. As such, ``execute_manager``is also deprecated; ``execute_from_command_line`` can be used instead. Neitherof these functions is documented as part of the public API, but a deprecationpath is needed due to use in existing ``manage.py`` files.``is_safe`` and ``needs_autoescape`` attributes of template filters-------------------------------------------------------------------Two flags, ``is_safe`` and ``needs_autoescape``, define how each template filterinteracts with Django's auto-escaping behavior. They used to be attributes ofthe filter function::@register.filterdef noop(value):return valuenoop.is_safe = TrueHowever, this technique caused some problems in combination with decorators,especially :func:`@stringfilter <django.template.defaultfilters.stringfilter>`.Now, the flags are keyword arguments of :meth:`@register.filter<django.template.Library.filter>`::@register.filter(is_safe=True)def noop(value):return valueSee :ref:`filters and auto-escaping <filters-auto-escaping>` for more information.Wildcard expansion of application names in ``INSTALLED_APPS``-------------------------------------------------------------Until Django 1.3, :setting:`INSTALLED_APPS` accepted wildcards in applicationnames, like ``django.contrib.*``. The expansion was performed by afilesystem-based implementation of ``from <package> import *``. Unfortunately,this can't be done reliably.This behavior was never documented. Since it is unpythonic, it was removed inDjango 1.4. If you relied on it, you must edit your settings file to list allyour applications explicitly.``HttpRequest.raw_post_data`` renamed to ``HttpRequest.body``-------------------------------------------------------------This attribute was confusingly named ``HttpRequest.raw_post_data``, but itactually provided the body of the HTTP request. It's been renamed to``HttpRequest.body``, and ``HttpRequest.raw_post_data`` has been deprecated.``django.contrib.sitemaps`` bug fix with potential performance implications---------------------------------------------------------------------------In previous versions, ``Paginator`` objects used in sitemap classes werecached, which could result in stale site maps. We've removed the caching, soeach request to a site map now creates a new Paginator object and calls the:attr:`~django.contrib.sitemaps.Sitemap.items()` method of the:class:`~django.contrib.sitemaps.Sitemap` subclass. Depending on what your``items()`` method is doing, this may have a negative performance impact.To mitigate the performance impact, consider using the :doc:`cachingframework </topics/cache>` within your ``Sitemap`` subclass.Versions of Python-Markdown earlier than 2.1--------------------------------------------Versions of Python-Markdown earlier than 2.1 do not support the option todisable attributes. As a security issue, earlier versions of this library willnot be supported by the markup contrib app in 1.5 under an accelerateddeprecation timeline.