December 1, 2015
Welcome to Django 1.9!
These release notes cover the new features, as well as some backwards incompatible changes you’ll want to be aware of when upgrading from Django 1.8 or older versions. We’ve dropped some features that have reached the end of their deprecation cycle, and we’ve begun the deprecation process for some features.
Django 1.9 requires Python 2.7, 3.4, or 3.5. We highly recommend and only officially support the latest release of each series.
Since Django 1.8, we’ve dropped support for Python 3.2 and 3.3.
The new on_commit() hook allows performing actions after a database transaction is successfully committed. This is useful for tasks such as sending notification emails, creating queued tasks, or invalidating caches.
This functionality from the django-transaction-hooks package has been integrated into Django.
Django now offers password validation to help prevent the usage of weak passwords by users. The validation is integrated in the included password change and reset forms and is simple to integrate in any other code. Validation is performed by one or more validators, configured in the new AUTH_PASSWORD_VALIDATORS setting.
Four validators are included in Django, which can enforce a minimum length, compare the password to the user’s attributes like their name, ensure passwords aren’t entirely numeric, or check against an included list of common passwords. You can combine multiple validators, and some validators have custom configuration options. For example, you can choose to provide a custom list of common passwords. Each validator provides a help text to explain its requirements to the user.
By default, no validation is performed and all passwords are accepted, so if you don’t set AUTH_PASSWORD_VALIDATORS, you will not see any change. In new projects created with the default startproject template, a simple set of validators is enabled. To enable basic validation in the included auth forms for your project, you could set, for example:
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
See Password validation for more details.
Django now ships with the mixins AccessMixin, LoginRequiredMixin, PermissionRequiredMixin, and UserPassesTestMixin to provide the functionality of the django.contrib.auth.decorators for class-based views. These mixins have been taken from, or are at least inspired by, the django-braces project.
There are a few differences between Django’s and django-braces’ implementation, though:
The admin sports a modern, flat design with new SVG icons which look perfect on HiDPI screens. It still provides a fully-functional experience to YUI’s A-grade browsers. Older browser may experience varying levels of graceful degradation.
The test command now supports a --parallel option to run a project’s tests in multiple processes in parallel.
Each process gets its own database. You must ensure that different test cases don’t access the same resources. For instance, test cases that touch the filesystem should create a temporary directory for their own use.
This option is enabled by default for Django’s own test suite provided:
Initial migrations are now marked with an initial = True class attribute which allows migrate --fake-initial to more easily detect initial migrations.
Added support for serialization of functools.partial and LazyObject instances.
When supplying None as a value in MIGRATION_MODULES, Django will consider the app an app without migrations.
When applying migrations, the “Rendering model states” step that’s displayed when running migrate with verbosity 2 or higher now computes only the states for the migrations that have already been applied. The model states for migrations being applied are generated on demand, drastically reducing the amount of required memory.
However, this improvement is not available when unapplying migrations and therefore still requires the precomputation and storage of the intermediate migration states.
This improvement also requires that Django no longer supports mixed migration plans. Mixed plans consist of a list of migrations where some are being applied and others are being unapplied. This was never officially supported and never had a public API that supports this behavior.
The squashmigrations command now supports specifying the starting migration from which migrations will be squashed.
Предупреждение
In addition to the changes outlined in this section, be sure to review the Features removed in 1.9 for the features that have reached the end of their deprecation cycle and therefore been removed. If you haven’t updated your code within the deprecation timeline for a given feature, its removal may appear as a backwards incompatible change.
A couple of new tests rely on the ability of the backend to introspect column defaults (returning the result as Field.default). You can set the can_introspect_default database feature to False if your backend doesn’t implement this. You may want to review the implementation on the backends that Django includes for reference (#24245).
Registering a global adapter or converter at the level of the DB-API module to handle time zone information of datetime values passed as query parameters or returned as query results on databases that don’t support time zones is discouraged. It can conflict with other libraries.
The recommended way to add a time zone to datetime values fetched from the database is to register a converter for DateTimeField in DatabaseOperations.get_db_converters().
The needs_datetime_string_cast database feature was removed. Database backends that set it must register a converter instead, as explained above.
The DatabaseOperations.value_to_db_<type>() methods were renamed to adapt_<type>field_value() to mirror the convert_<type>field_value() methods.
To use the new date lookup, third-party database backends may need to implement the DatabaseOperations.datetime_cast_date_sql() method.
The DatabaseOperations.time_extract_sql() method was added. It calls the existing date_extract_sql() method. This method is overridden by the SQLite backend to add time lookups (hour, minute, second) to TimeField, and may be needed by third-party database backends.
The DatabaseOperations.datetime_cast_sql() method (not to be confused with DatabaseOperations.datetime_cast_date_sql() mentioned above) has been removed. This method served to format dates on Oracle long before 1.0, but hasn’t been overridden by any core backend in years and hasn’t been called anywhere in Django’s code or tests.
In order to support test parallelization, you must implement the DatabaseCreation._clone_test_db() method and set DatabaseFeatures.can_clone_databases = True. You may have to adjust DatabaseCreation.get_test_db_clone_settings().
The default settings in django.conf.global_settings were a combination of lists and tuples. All settings that were formerly tuples are now lists.
Django template loaders previously required an is_usable attribute to be defined. If a loader was configured in the template settings and this attribute was False, the loader would be silently ignored. In practice, this was only used by the egg loader to detect if setuptools was installed. The is_usable attribute is now removed and the egg loader instead fails at runtime if setuptools is not installed.
When using the filesystem.Loader or app_directories.Loader template loaders, earlier versions of Django raised a TemplateDoesNotExist error if a template source existed but was unreadable. This could happen under many circumstances, such as if Django didn’t have permissions to open the file, or if the template source was a directory. Now, Django only silences the exception if the template source does not exist. All other situations result in the original IOError being raised.
Relative redirects are no longer converted to absolute URIs. RFC 2616 required the Location header in redirect responses to be an absolute URI, but it has been superseded by RFC 7231 which allows relative URIs in Location, recognizing the actual practice of user agents, almost all of which support them.
Consequently, the expected URLs passed to assertRedirects should generally no longer include the scheme and domain part of the URLs. For example, self.assertRedirects(response, 'http://testserver/some-url/') should be replaced by self.assertRedirects(response, '/some-url/') (unless the redirection specifically contained an absolute URL, of course).
Upstream support for PostgreSQL 9.0 ended in September 2015. As a consequence, Django 1.9 sets 9.1 as the minimum PostgreSQL version it officially supports.
Upstream support for Oracle 11.1 ended in August 2015. As a consequence, Django 1.9 sets 11.2 as the minimum Oracle version it officially supports.
In previous versions of Django, when a template engine was initialized with debug as True, an instance of django.template.loader.LoaderOrigin or django.template.base.StringOrigin was set as the origin attribute on the template object. These classes have been combined into Origin and is now always set regardless of the engine debug setting. For a minimal level of backwards compatibility, the old class names will be kept as aliases to the new Origin class until Django 2.0.
To make it easier to write custom logging configurations, Django’s default logging configuration no longer defines ‘django.request’ and ‘django.security’ loggers. Instead, it defines a single ‘django’ logger, filtered at the INFO level, with two handlers:
If you aren’t overriding Django’s default logging, you should see minimal changes in behavior, but you might see some new logging to the runserver console, for example.
If you are overriding Django’s default logging, you should check to see how your configuration merges with the new defaults.
It was redundant to display the full details of the HttpRequest each time it appeared as a stack frame variable in the HTML version of the debug page and error email. Thus, the HTTP request will now display the same standard representation as other variables (repr(request)). As a result, the method ExceptionReporterFilter.get_request_repr() was removed.
The contents of the text version of the email were modified to provide a traceback of the same structure as in the case of AJAX requests. The traceback details are rendered by the ExceptionReporter.get_traceback_text() method.
Django no longer registers global adapters and converters for managing time zone information on datetime values sent to the database as query parameters or read from the database in query results. This change affects projects that meet all the following conditions:
If you’re passing aware datetime parameters to such queries, you should turn them into naive datetimes in UTC:
from django.utils import timezone
param = timezone.make_naive(param, timezone.utc)
If you fail to do so, the conversion will be performed as in earlier versions (with a deprecation warning) up until Django 1.11. Django 2.0 won’t perform any conversion, which may result in data corruption.
If you’re reading datetime values from the results, they will be naive instead of aware. You can compensate as follows:
from django.utils import timezone
value = timezone.make_aware(value, timezone.utc)
You don’t need any of this if you’re querying the database through the ORM, even if you’re using raw() queries. The ORM takes care of managing time zone information.
The DjangoTemplates backend now performs discovery on installed template tag modules when instantiated. This update enables libraries to be provided explicitly via the 'libraries' key of OPTIONS when defining a DjangoTemplates backend. Import or syntax errors in template tag modules now fail early at instantiation time rather than when a template with a {% load %} tag is first compiled.
Although it was a private API, projects commonly used add_to_builtins() to make template tags and filters available without using the {% load %} tag. This API has been formalized. Projects should now define built-in libraries via the 'builtins' key of OPTIONS when defining a DjangoTemplates backend.
In general, template tags do not autoescape their contents, and this behavior is documented. For tags like inclusion_tag, this is not a problem because the included template will perform autoescaping. For assignment_tag, the output will be escaped when it is used as a variable in the template.
For the intended use cases of simple_tag, however, it is very easy to end up with incorrect HTML and possibly an XSS exploit. For example:
@register.simple_tag(takes_context=True)
def greeting(context):
return "Hello {0}!".format(context['request'].user.first_name)
In older versions of Django, this will be an XSS issue because user.first_name is not escaped.
In Django 1.9, this is fixed: if the template context has autoescape=True set (the default), then simple_tag will wrap the output of the tag function with conditional_escape().
To fix your simple_tags, it is best to apply the following practices:
Tags that follow these rules will be correct and safe whether they are run on Django 1.9+ or earlier.
Paginator.page_range is now an iterator instead of a list.
In versions of Django previous to 1.8, Paginator.page_range returned a list in Python 2 and a range in Python 3. Django 1.8 consistently returned a list, but an iterator is more efficient.
Existing code that depends on list specific features, such as indexing, can be ported by converting the iterator into a list using list().
In earlier versions, queries such as:
Model.objects.filter(related_id=RelatedModel.objects.all())
would implicitly convert to:
Model.objects.filter(related_id__in=RelatedModel.objects.all())
resulting in SQL like "related_id IN (SELECT id FROM ...)".
This implicit __in no longer happens so the “IN” SQL is now “=”, and if the subquery returns multiple results, at least some databases will throw an error.
The admin no longer supports Internet Explorer 8 and below, as these browsers have reached end-of-life.
CSS and images to support Internet Explorer 6 and 7 have been removed. PNG and GIF icons have been replaced with SVG icons, which are not supported by Internet Explorer 8 and earlier.
The jQuery library embedded in the admin has been upgraded from version 1.11.2 to 2.1.4. jQuery 2.x has the same API as jQuery 1.x, but does not support Internet Explorer 6, 7, or 8, allowing for better performance and a smaller file size. If you need to support IE8 and must also use the latest version of Django, you can override the admin’s copy of jQuery with your own by creating a Django application with this structure:
app/static/admin/js/vendor/
jquery.js
jquery.min.js
When installing Django 1.9+ with pip ≤ 1.5.6, you’ll see:
Compiling django/conf/app_template/apps.py ...
File "django/conf/app_template/apps.py", line 4
class {{ camel_case_app_name }}Config(AppConfig):
^
SyntaxError: invalid syntax
Compiling django/conf/app_template/models.py ...
File "django/conf/app_template/models.py", line 1
{{ unicode_literals }}from django.db import models
^
SyntaxError: invalid syntax
It’s safe to ignore these errors (Django will still install just fine), and you can avoid them by upgrading pip to a more recent version using pip install -U pip.
Django 1.4 added the assignment_tag helper to ease the creation of template tags that store results in a template variable. The simple_tag() helper has gained this same ability, making the assignment_tag obsolete. Tags that use assignment_tag should be updated to use simple_tag.
The cycle tag supports an inferior old syntax from previous Django versions:
{% cycle row1,row2,row3 %}
Its parsing caused bugs with the current syntax, so support for the old syntax will be removed in Django 1.10 following an accelerated deprecation.
In order to increase awareness about cascading model deletion, the on_delete argument of ForeignKey and OneToOneField will be required in Django 2.0.
Update models and existing migrations to explicitly set the argument. Since the default is models.CASCADE, add on_delete=models.CASCADE to all ForeignKey and OneToOneFields that don’t use a different option. You can also pass it as the second positional argument if you don’t care about compatibility with older versions of Django.
Field.rel and its methods and attributes have changed to match the related fields API. The Field.rel attribute is renamed to remote_field and many of its methods and attributes are either changed or renamed.
The aim of these changes is to provide a documented API for relation fields.
All custom GeoQuerySet methods (area(), distance(), gml(), ...) have been replaced by equivalent geographic expressions in annotations (see in new features). Hence the need to set a custom GeoManager to GIS-enabled models is now obsolete. As soon as your code doesn’t call any of the deprecated methods, you can simply remove the objects = GeoManager() lines from your models.
Django template loaders have been updated to allow recursive template extending. This change necessitated a new template loader API. The old load_template() and load_template_sources() methods are now deprecated. Details about the new API can be found in the template loader documentation.
The instance namespace part of passing a tuple as an argument to include() has been replaced by passing the namespace argument to include(). For example:
polls_patterns = [
url(...),
]
urlpatterns = [
url(r'^polls/', include((polls_patterns, 'polls', 'author-polls'))),
]
becomes:
polls_patterns = ([
url(...),
], 'polls') # 'polls' is the app_name
urlpatterns = [
url(r'^polls/', include(polls_patterns, namespace='author-polls')),
]
The app_name argument to include() has been replaced by passing a 2-tuple (as above), or passing an object or module with an app_name attribute (as below). If the app_name is set in this new way, the namespace argument is no longer required. It will default to the value of app_name. For example, the URL patterns in the tutorial are changed from:
urlpatterns = [
url(r'^polls/', include('polls.urls', namespace="polls")),
...
]
to:
urlpatterns = [
url(r'^polls/', include('polls.urls')), # 'namespace="polls"' removed
...
]
app_name = 'polls' # added
urlpatterns = [...]
This change also means that the old way of including an AdminSite instance is deprecated. Instead, pass admin.site.urls directly to url():
from django.conf.urls import url
from django.contrib import admin
urlpatterns = [
url(r'^admin/', admin.site.urls),
]
In the past, an instance namespace without an application namespace would serve the same purpose as the application namespace, but it was impossible to reverse the patterns if there was an application namespace with the same name. Includes that specify an instance namespace require that the included URLconf sets an application namespace.
All views in django.contrib.auth.views have the following structure:
def view(request, ..., current_app=None, ...):
...
if current_app is not None:
request.current_app = current_app
return TemplateResponse(request, template_name, context)
As of Django 1.8, current_app is set on the request object. For consistency, these views will require the caller to set current_app on the request instead of passing it in a separate argument.
The django.contrib.gis.geoip2 module supersedes django.contrib.gis.geoip. The new module provides a similar API except that it doesn’t provide the legacy GeoIP-Python API compatibility methods.
These features have reached the end of their deprecation cycle and so have been removed in Django 1.9 (please see the deprecation timeline for more details):
Mar 31, 2016