Django 1.9 版本发行说明

Django 1.9 版本发行说明

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 更新至新的版本 指南。

Python 兼容性

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.

The Django 1.8 series is the last to support Python 3.2 and 3.3.

What’s new in Django 1.9

Performing actions after a transaction commit

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 密码验证 for more details.

Permission mixins for class-based views

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 raise_exception attribute can only be True or False. Custom exceptions or callables are not supported.
  • The handle_no_permission() method does not take a request argument. The current request is available in self.request.
  • The custom test_func() of UserPassesTestMixin does not take a user argument. The current user is available in self.request.user.
  • The permission_required attribute supports a string (defining one permission) or a list/tuple of strings (defining multiple permissions) that need to be fulfilled to grant access.
  • The new permission_denied_message attribute allows passing a message to the PermissionDenied exception.

New styling for contrib.admin

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.

每个进程都会得到它们自己的数据库。你必须确保不同的测试用例不会访问相同的资源。例如,接触文件系统的测试用例应该创建一个临时目录供自己使用。

This option is enabled by default for Django’s own test suite provided:

  • the OS supports it (all but Windows)
  • the database backend supports it (all the built-in backends but Oracle)

次要特性

django.contrib.admin

  • Admin views now have model_admin or admin_site attributes.
  • The URL of the admin change view has been changed (was at /admin/<app>/<model>/<pk>/ by default and is now at /admin/<app>/<model>/<pk>/change/). This should not affect your application unless you have hardcoded admin URLs. In that case, replace those links by reversing admin URLs instead. Note that the old URL still redirects to the new one for backwards compatibility, but it may be removed in a future version.
  • ModelAdmin.get_list_select_related() was added to allow changing the select_related() values used in the admin’s changelist query based on the request.
  • The available_apps context variable, which lists the available applications for the current user, has been added to the AdminSite.each_context() method.
  • AdminSite.empty_value_display and ModelAdmin.empty_value_display were added to override the display of empty values in admin change list. You can also customize the value for each field.
  • Added jQuery events when an inline form is added or removed on the change form page.
  • The time picker widget includes a ‘6 p.m’ option for consistency of having predefined options every 6 hours.
  • JavaScript slug generation now supports Romanian characters.

django.contrib.admindocs

  • The model section of the admindocs now also describes methods that take arguments, rather than ignoring them.

django.contrib.auth

  • The default iteration count for the PBKDF2 password hasher has been increased by 20%. This backwards compatible change will not affect users who have subclassed django.contrib.auth.hashers.PBKDF2PasswordHasher to change the default value.
  • The BCryptSHA256PasswordHasher will now update passwords if its rounds attribute is changed.
  • AbstractBaseUser and BaseUserManager were moved to a new django.contrib.auth.base_user module so that they can be imported without including django.contrib.auth in INSTALLED_APPS (doing so raised a deprecation warning in older versions and is no longer supported in Django 1.9).
  • The permission argument of permission_required() accepts all kinds of iterables, not only list and tuples.
  • The new PersistentRemoteUserMiddleware makes it possible to use REMOTE_USER for setups where the header is only populated on login pages instead of every request in the session.
  • The django.contrib.auth.views.password_reset() view accepts an extra_email_context parameter.

django.contrib.contenttypes

django.contrib.gis

  • All GeoQuerySet methods have been deprecated and replaced by equivalent database functions. As soon as the legacy methods have been replaced in your code, you should even be able to remove the special GeoManager from your GIS-enabled classes.
  • The GDAL interface now supports instantiating file-based and in-memory GDALRaster objects from raw data. Setters for raster properties such as projection or pixel values have been added.
  • For PostGIS users, the new RasterField allows storing GDALRaster objects. It supports automatic spatial index creation and reprojection when saving a model. It does not yet support spatial querying.
  • The new GDALRaster.warp() method allows warping a raster by specifying target raster properties such as origin, width, height, or pixel size (among others).
  • The new GDALRaster.transform() method allows transforming a raster into a different spatial reference system by specifying a target srid.
  • The new GeoIP2 class allows using MaxMind’s GeoLite2 databases which includes support for IPv6 addresses.
  • The default OpenLayers library version included in widgets has been updated from 2.13 to 2.13.1.

django.contrib.postgres

django.contrib.sessions

  • The session model and SessionStore classes for the db and cached_db backends are refactored to allow a custom database session backend to build upon them. See 扩展数据库支持的会话引擎 for more details.

django.contrib.sites

  • get_current_site() now handles the case where request.get_host() returns domain:port, e.g. example.com:80. If the lookup fails because the host does not match a record in the database and the host has a port, the port is stripped and the lookup is retried with the domain part only.

django.contrib.syndication

  • Support for multiple enclosures per feed item has been added. If multiple enclosures are defined on a RSS feed, an exception is raised as RSS feeds, unlike Atom feeds, do not support multiple enclosures per feed item.

缓存

  • django.core.cache.backends.base.BaseCache now has a get_or_set() method.
  • django.views.decorators.cache.never_cache() now sends more persuasive headers (added no-cache, no-store, must-revalidate to Cache-Control) to better prevent caching. This was also added in Django 1.8.8.

CSRF

  • The request header’s name used for CSRF authentication can be customized with CSRF_HEADER_NAME.
  • The CSRF referer header is now validated against the CSRF_COOKIE_DOMAIN setting if set. See 工作方式 for details.
  • The new CSRF_TRUSTED_ORIGINS setting provides a way to allow cross-origin unsafe requests (e.g. POST) over HTTPS.

数据库后端

  • The PostgreSQL backend (django.db.backends.postgresql_psycopg2) is also available as django.db.backends.postgresql. The old name will continue to be available for backwards compatibility.

文件存储

表单

  • ModelForm accepts the new Meta option field_classes to customize the type of the fields. See 覆盖默认字段 for details.
  • You can now specify the order in which form fields are rendered with the field_order attribute, the field_order constructor argument , or the order_fields() method.
  • A form prefix can be specified inside a form class, not only when instantiating a form. See 表单前缀 for details.
  • You can now specify keyword arguments that you want to pass to the constructor of forms in a formset.
  • SlugField now accepts an allow_unicode argument to allow Unicode characters in slugs.
  • CharField now accepts a strip argument to strip input data of leading and trailing whitespace. As this defaults to True this is different behavior from previous releases.
  • Form fields now support the disabled argument, allowing the field widget to be displayed disabled by browsers.
  • It’s now possible to customize bound fields by overriding a field’s get_bound_field() method.

通用视图

国际化

  • The django.views.i18n.set_language() view now properly redirects to translated URLs, when available.
  • The django.views.i18n.javascript_catalog() view now works correctly if used multiple times with different configurations on the same page.
  • The django.utils.timezone.make_aware() function gained an is_dst argument to help resolve ambiguous times during DST transitions.
  • You can now use locale variants supported by gettext. These are usually used for languages which can be written in different scripts, for example Latin and Cyrillic (e.g. be@latin).
  • Added the django.views.i18n.json_catalog() view to help build a custom client-side i18n library upon Django translations. It returns a JSON object containing a translations catalog, formatting settings, and a plural rule.
  • Added the name_translated attribute to the object returned by the get_language_info template tag. Also added a corresponding template filter: language_name_translated.
  • You can now run compilemessages from the root directory of your project and it will find all the app message files that were created by makemessages.
  • makemessages now calls xgettext once per locale directory rather than once per translatable file. This speeds up localization builds.
  • blocktrans supports assigning its output to a variable using asvar.
  • Two new languages are available: Colombian Spanish and Scottish Gaelic.

管理命令

  • The new sendtestemail command lets you send a test email to easily confirm that email sending through Django is working.
  • To increase the readability of the SQL code generated by sqlmigrate, the SQL code generated for each migration operation is preceded by the operation’s description.
  • The dumpdata command output is now deterministically ordered. Moreover, when the --output option is specified, it also shows a progress bar in the terminal.
  • The createcachetable command now has a --dry-run flag to print out the SQL rather than execute it.
  • The startapp command creates an apps.py file. Since it doesn’t use default_app_config (a discouraged API), you must specify the app config’s path, e.g. 'polls.apps.PollsConfig', in INSTALLED_APPS for it to be used (instead of just 'polls').
  • When using the PostgreSQL backend, the dbshell command can connect to the database using the password from your settings file (instead of requiring it to be manually entered).
  • The django package may be run as a script, i.e. python -m django, which will behave the same as django-admin.
  • Management commands that have the --noinput option now also take --no-input as an alias for that option.

迁移

  • 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.

模型

  • QuerySet.bulk_create() now works on proxy models.
  • Database configuration gained a TIME_ZONE option for interacting with databases that store datetimes in local time and don’t support time zones when USE_TZ is True.
  • Added the RelatedManager.set() method to the related managers created by ForeignKey, GenericForeignKey, and ManyToManyField.
  • The add() method on a reverse foreign key now has a bulk parameter to allow executing one query regardless of the number of objects being added rather than one query per object.
  • Added the keep_parents parameter to Model.delete() to allow deleting only a child’s data in a model that uses multi-table inheritance.
  • Model.delete() and QuerySet.delete() return the number of objects deleted.
  • Added a system check to prevent defining both Meta.ordering and order_with_respect_to on the same model.
  • Date and time lookups can be chained with other lookups (such as exact, gt, lt, etc.). For example: Entry.objects.filter(pub_date__month__gt=6).
  • Time lookups (hour, minute, second) are now supported by TimeField for all database backends. Support for backends other than SQLite was added but undocumented in Django 1.7.
  • You can specify the output_field parameter of the Avg aggregate in order to aggregate over non-numeric columns, such as DurationField.
  • Added the date lookup to DateTimeField to allow querying the field by only the date portion.
  • Added the Greatest and Least database functions.
  • Added the Now database function, which returns the current date and time.
  • Transform is now a subclass of Func() which allows Transforms to be used on the right hand side of an expression, just like regular Funcs. This allows registering some database functions like Length, Lower, and Upper as transforms.
  • SlugField now accepts an allow_unicode argument to allow Unicode characters in slugs.
  • Added support for referencing annotations in QuerySet.distinct().
  • connection.queries shows queries with substituted parameters on SQLite.
  • Query expressions can now be used when creating new model instances using save(), create(), and bulk_create().

请求和响应

  • Unless HttpResponse.reason_phrase is explicitly set, it now is determined by the current value of HttpResponse.status_code. Modifying the value of status_code outside of the constructor will also modify the value of reason_phrase.
  • The debug view now shows details of chained exceptions on Python 3.
  • The default 40x error views now accept a second positional parameter, the exception that triggered the view.
  • View error handlers now support TemplateResponse, commonly used with class-based views.
  • Exceptions raised by the render() method are now passed to the process_exception() method of each middleware.
  • Request middleware can now set HttpRequest.urlconf to None to revert any changes made by previous middleware and return to using the ROOT_URLCONF.
  • The DISALLOWED_USER_AGENTS check in CommonMiddleware now raises a PermissionDenied exception as opposed to returning an HttpResponseForbidden so that handler403 is invoked.
  • Added HttpRequest.get_port() to fetch the originating port of the request.
  • Added the json_dumps_params parameter to JsonResponse to allow passing keyword arguments to the json.dumps() call used to generate the response.
  • The BrokenLinkEmailsMiddleware now ignores 404s when the referer is equal to the requested URL. To circumvent the empty referer check already implemented, some web bots set the referer to the requested URL.

模板

  • Template tags created with the simple_tag() helper can now store results in a template variable by using the as argument.
  • Added a Context.setdefault() method.
  • The django.template logger was added and includes the following messages:
    • A DEBUG level message for missing context variables.
    • A WARNING level message for uncaught exceptions raised during the rendering of an {% include %} when debug mode is off (helpful since {% include %} silences the exception and returns an empty string).
  • The firstof template tag supports storing the output in a variable using ‘as’.
  • Context.update() can now be used as a context manager.
  • Django template loaders can now extend templates recursively.
  • The debug page template postmortem now include output from each engine that is installed.
  • Debug page integration for custom template engines was added.
  • The DjangoTemplates backend gained the ability to register libraries and builtins explicitly through the template OPTIONS.
  • The timesince and timeuntil filters were improved to deal with leap years when given large time spans.
  • The include tag now caches parsed templates objects during template rendering, speeding up reuse in places such as for loops.

测试

  • Added the json() method to test client responses to give access to the response body as JSON.
  • Added the force_login() method to the test client. Use this method to simulate the effect of a user logging into the site while skipping the authentication and verification steps of login().

URLs

  • Regular expression lookaround assertions are now allowed in URL patterns.
  • The application namespace can now be set using an app_name attribute on the included module or object. It can also be set by passing a 2-tuple of (<list of patterns>, <application namespace>) as the first argument to include().
  • System checks have been added for common URL pattern mistakes.

验证器

Backwards incompatible changes in 1.9

警告

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.

数据库后端 API

  • 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().

Default settings that were tuples are now lists

The default settings in django.conf.global_settings were a combination of lists and tuples. All settings that were formerly tuples are now lists.

is_usable attribute on template loaders is removed

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.

Direct assignment of related objects in the ORM used to perform a clear() followed by a call to add(). This caused needlessly large data changes and prevented using the m2m_changed signal to track individual changes in many-to-many relations.

Direct assignment now relies on the new set() method on related managers which by default only processes changes between the existing related set and the one that’s newly assigned. The previous behavior can be restored by replacing direct assignment by a call to set() with the keyword argument clear=True.

ModelForm, and therefore ModelAdmin, internally rely on direct assignment for many-to-many relations and as a consequence now use the new behavior.

(本文超出站点单文档体积上限,已按小节截断)