Django 1.8 版本发行说明

Django 1.8 版本发行说明

April 1, 2015

Welcome to Django 1.8!

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.7 or older versions. We’ve also begun the deprecation process for some features, and some features have reached the end of their deprecation process and have been removed.

如果你要更新现有的项目,请看 如何将 Django 更新至新的版本 指南。

Django 1.8 has been designated as Django’s second long-term support release. It will receive security updates for at least three years after its release. Support for the previous LTS, Django 1.4, will end 6 months from the release date of Django 1.8.

Python 兼容性

Django 1.8 requires Python 2.7, 3.2, 3.3, 3.4, or 3.5. We highly recommend and only officially support the latest release of each series.

Django 1.8 is the first release to support Python 3.5.

Due to the end of upstream support for Python 3.2 in February 2016, we won’t test Django 1.8.x on Python 3.2 after the end of 2016.

What’s new in Django 1.8

Model._meta API

Django now has a formalized API for Model._meta, providing an officially supported way to retrieve fields and filter fields based on their attributes.

The Model._meta object has been part of Django since the days of pre-0.96 “Magic Removal” — it just wasn’t an official, stable API. In recognition of this, we’ve endeavored to maintain backwards-compatibility with the old API endpoint where possible. However, API endpoints that aren’t part of the new official API have been deprecated and will eventually be removed.

Multiple template engines

Django 1.8 defines a stable API for integrating template backends. It includes built-in support for the Django template language and for Jinja2. It supports rendering templates with multiple engines within the same project. Learn more about the new features in the topic guide and check the upgrade instructions in older versions of the documentation.

Security enhancements

Several features of the django-secure third-party library have been integrated into Django. django.middleware.security.SecurityMiddleware provides several security enhancements to the request/response cycle. The new check —deploy option allows you to check your production settings file for ways to increase the security of your site.

New PostgreSQL specific functionality

Django now has a module with extensions for PostgreSQL specific features, such as ArrayField, HStoreField, 范围字段, and unaccent lookup. A full breakdown of the features is available in the documentation.

New data types

  • Django now has a UUIDField for storing universally unique identifiers. It is stored as the native uuid data type on PostgreSQL and as a fixed length character field on other backends. There is a corresponding form field.
  • Django now has a DurationField for storing periods of time - modeled in Python by timedelta. It is stored in the native interval data type on PostgreSQL, as a INTERVAL DAY(9) TO SECOND(6) on Oracle, and as a bigint of microseconds on other backends. Date and time related arithmetic has also been improved on all backends. There is a corresponding form field.

Query Expressions, Conditional Expressions, and Database Functions

Query Expressions allow you to create, customize, and compose complex SQL expressions. This has enabled annotate to accept expressions other than aggregates. Aggregates are now able to reference multiple fields, as well as perform arithmetic, similar to F() objects. order_by() has also gained the ability to accept expressions.

Conditional Expressions allow you to use if … elif … else logic within queries.

A collection of database functions is also included with functionality such as Coalesce, Concat, and Substr.

TestCase data setup

TestCase has been refactored to allow for data initialization at the class level using transactions and savepoints. Database backends which do not support transactions, like MySQL with the MyISAM storage engine, will still be able to run these tests but won’t benefit from the improvements. Tests are now run within two nested atomic() blocks: one for the whole class and one for each test.

  • The class method TestCase.setUpTestData() adds the ability to set up test data at the class level. Using this technique can speed up the tests as compared to using setUp().
  • Fixture loading within TestCase is now performed once for the whole TestCase.

次要特性

django.contrib.admin

  • ModelAdmin now has a has_module_permission() method to allow limiting access to the module on the admin index page.
  • InlineModelAdmin now has an attribute show_change_link that supports showing a link to an inline object’s change form.
  • Use the new django.contrib.admin.RelatedOnlyFieldListFilter in ModelAdmin.list_filter to limit the list_filter choices to foreign objects which are attached to those from the ModelAdmin.
  • The ModelAdmin.delete_view() displays a summary of objects to be deleted on the deletion confirmation page.
  • The jQuery library embedded in the admin has been upgraded to version 1.11.2.
  • You can now specify AdminSite.site_url in order to display a link to the front-end site.
  • You can now specify ModelAdmin.show_full_result_count to control whether or not the full count of objects should be displayed on a filtered admin page.
  • The AdminSite.password_change() method now has an extra_context parameter.
  • You can now control who may login to the admin site by overriding only AdminSite.has_permission() and AdminSite.login_form. The base.html template has a new block usertools which contains the user-specific header. A new context variable has_permission, which gets its value from has_permission(), indicates whether the user may access the site.
  • Foreign key dropdowns now have buttons for changing or deleting related objects using a popup.

django.contrib.admindocs

  • reStructuredText is now parsed in model docstrings.

django.contrib.auth

  • Authorization backends can now raise PermissionDenied in has_perm() and has_module_perms() to short-circuit permission checking.
  • PasswordResetForm now has a method send_mail() that can be overridden to customize the mail to be sent.
  • The max_length of Permission.name has been increased from 50 to 255 characters. Please run the database migration.
  • USERNAME_FIELD and REQUIRED_FIELDS now supports ForeignKeys.
  • The default iteration count for the PBKDF2 password hasher has been increased by 33%. This backwards compatible change will not affect users who have subclassed django.contrib.auth.hashers.PBKDF2PasswordHasher to change the default value.

django.contrib.gis

  • A new GeoJSON serializer is now available.
  • It is now allowed to include a subquery as a geographic lookup argument, for example City.objects.filter(point__within=Country.objects.filter(continent='Africa').values('mpoly')).
  • The SpatiaLite backend now supports Collect and Extent aggregates when the database version is 3.0 or later.
  • The PostGIS 2 CREATE EXTENSION postgis and the SpatiaLite SELECT InitSpatialMetaData initialization commands are now automatically run by migrate.
  • The GDAL interface now supports retrieving properties of raster (image) data file.
  • Compatibility shims for SpatialRefSys and GeometryColumns changed in Django 1.2 have been removed.
  • All GDAL-related exceptions are now raised with GDALException. The former OGRException has been kept for backwards compatibility but should not be used any longer.

django.contrib.sessions

  • Session cookie is now deleted after flush() is called.

django.contrib.sitemaps

django.contrib.sites

缓存

  • The incr() method of the django.core.cache.backends.locmem.LocMemCache backend is now thread-safe.

Cryptography

数据库后端

  • The MySQL backend no longer strips microseconds from datetime values as MySQL 5.6.4 and up supports fractional seconds depending on the declaration of the datetime field (when DATETIME includes fractional precision greater than 0). New datetime database columns created with Django 1.8 and MySQL 5.6.4 and up will support microseconds. See the MySQL database notes for more details.
  • The MySQL backend no longer creates explicit indexes for foreign keys when using the InnoDB storage engine, as MySQL already creates them automatically.
  • The Oracle backend no longer defines the connection_persists_old_columns feature as True. Instead, Oracle will now include a cache busting clause when getting the description of a table.

电子邮件

文件存储

  • Storage.get_available_name() and Storage.save() now take a max_length argument to implement storage-level maximum filename length constraints. Filenames exceeding this argument will get truncated. This prevents a database error when appending a unique suffix to a long filename that already exists on the storage. See the deprecation note about adding this argument to your custom storage classes.

表单

  • Form widgets now render attributes with a value of True or False as HTML5 boolean attributes.
  • The new has_error() method allows checking if a specific error has happened.
  • If required_css_class is defined on a form, then the <label> tags for required fields will have this class present in its attributes.
  • The rendering of non-field errors in unordered lists (<ul>) now includes nonfield in its list of classes to distinguish them from field-specific errors.
  • Field now accepts a label_suffix argument, which will override the form’s label_suffix. This enables customizing the suffix on a per-field basis — previously it wasn’t possible to override a form’s label_suffix while using shortcuts such as {{ form.as_p }} in templates.
  • SelectDateWidget now accepts an empty_label argument, which will override the top list choice label when DateField is not required.
  • After an ImageField has been cleaned and validated, the UploadedFile object will have an additional image attribute containing the Pillow Image instance used to check if the file was a valid image. It will also update UploadedFile.content_type with the image’s content type as determined by Pillow.
  • You can now pass a callable that returns an iterable of choices when instantiating a ChoiceField.

通用视图

国际化

  • FORMAT_MODULE_PATH can now be a list of strings representing module paths. This allows importing several format modules from different reusable apps. It also allows overriding those custom formats in your main Django project.

日志

管理命令

  • Database connections are now always closed after a management command called from the command line has finished doing its job.
  • Commands from alternate package formats like eggs are now also discovered.
  • The new dumpdata —output option allows specifying a file to which the serialized data is written.
  • The new makemessages —exclude and compilemessages —exclude options allow excluding specific locales from processing.
  • compilemessages now has a --use-fuzzy or -f option which includes fuzzy translations into compiled files.
  • The loaddata —ignorenonexistent option now ignores data for models that no longer exist.
  • runserver now uses daemon threads for faster reloading.
  • inspectdb now outputs Meta.unique_together. It is also able to introspect AutoField for MySQL and PostgreSQL databases.
  • When calling management commands with options using call_command(), the option name can match the command line option name (without the initial dashes) or the final option destination variable name, but in either case, the resulting option received by the command is now always the dest name specified in the command option definition (as long as the command uses the argparse module).
  • The dbshell command now supports MySQL’s optional SSL certificate authority setting (--ssl-ca).
  • The new makemigrations —name allows giving the migration(s) a custom name instead of a generated one.
  • The loaddata command now prevents repeated fixture loading. If FIXTURE_DIRS contains duplicates or a default fixture directory path (app_name/fixtures), an exception is raised.
  • The new makemigrations --exit option allows exiting with an error code if no migrations are created.
  • The new showmigrations command allows listing all migrations and their dependencies in a project.

中间件

迁移

  • The RunSQL operation can now handle parameters passed to the SQL statements.
  • It is now possible to have migrations (most probably data migrations) for applications without models.
  • Migrations can now serialize model managers as part of the model state.
  • A generic mechanism to handle the deprecation of model fields was added.
  • The RunPython.noop() and RunSQL.noop class method/attribute were added to ease in making RunPython and RunSQL operations reversible.
  • The migration operations RunPython and RunSQL now call the allow_migrate() method of database routers. The router can use the newly introduced app_label and hints arguments to make a routing decision. To take advantage of this feature you need to update the router to the new allow_migrate signature, see the deprecation section for more details.

模型

  • Django now logs at most 9000 queries in connections.queries, in order to prevent excessive memory usage in long-running processes in debug mode.
  • There is now a model Meta option to define a default related name for all relational fields of a model.
  • Pickling models and querysets across different versions of Django isn’t officially supported (it may work, but there’s no guarantee). An extra variable that specifies the current Django version is now added to the pickled state of models and querysets, and Django raises a RuntimeWarning when these objects are unpickled in a different version than the one in which they were pickled.
  • Added Model.from_db() which Django uses whenever objects are loaded using the ORM. The method allows customizing model loading behavior.
  • extra(select={...}) now allows you to escape a literal %s sequence using %%s.
  • Custom Lookups can now be registered using a decorator pattern.
  • The new Transform.bilateral attribute allows creating bilateral transformations. These transformations are applied to both lhs and rhs when used in a lookup expression, providing opportunities for more sophisticated lookups.
  • SQL special characters (, %, _) are now escaped properly when a pattern lookup (e.g. contains, startswith, etc.) is used with an F() expression as the right-hand side. In those cases, the escaping is performed by the database, which can lead to somewhat complex queries involving nested REPLACE function calls.
  • You can now refresh model instances by using Model.refresh_from_db().
  • You can now get the set of deferred fields for a model using Model.get_deferred_fields().
  • Model field default’s are now used when primary key field’s are set to None.

信号

  • Exceptions from the (receiver, exception) tuples returned by Signal.send_robust() now have their traceback attached as a __traceback__ attribute.
  • The environ argument, which contains the WSGI environment structure from the request, was added to the request_started signal.
  • You can now import the setting_changed() signal from django.core.signals to avoid loading django.test in non-test situations. Django no longer does so itself.

System Check Framework

  • register can now be used as a function.

模板

  • urlize now supports domain-only links that include characters after the top-level domain (e.g. djangoproject.com/ and djangoproject.com/download/).
  • urlize doesn’t treat exclamation marks at the end of a domain or its query string as part of the URL (the URL in e.g. 'djangoproject.com! is djangoproject.com)
  • Added a locmem.Loader class that loads Django templates from a Python dictionary.
  • The now tag can now store its output in a context variable with the usual syntax: {% now 'j n Y' as varname %}.

请求和响应

  • WSGIRequest now respects paths starting with //.
  • The HttpRequest.build_absolute_uri() method now handles paths starting with // correctly.
  • If DEBUG is True and a request raises a SuspiciousOperation, the response will be rendered with a detailed error page.
  • The query_string argument of QueryDict is now optional, defaulting to None, so a blank QueryDict can now be instantiated with QueryDict() instead of QueryDict(None) or QueryDict('').
  • The GET and POST attributes of an HttpRequest object are now QueryDicts rather than dictionaries, and the FILES attribute is now a MultiValueDict. This brings this class into line with the documentation and with WSGIRequest.
  • The HttpResponse.charset attribute was added.
  • WSGIRequestHandler now follows RFC in converting URI to IRI, using uri_to_iri().
  • The HttpRequest.get_full_path() method now escapes unsafe characters from the path portion of a Uniform Resource Identifier (URI) properly.
  • HttpResponse now implements a few additional methods like getvalue() so that instances can be used as stream objects.
  • The new HttpResponse.setdefault() method allows setting a header unless it has already been set.
  • You can use the new FileResponse to stream files.
  • The condition() decorator for conditional view processing now supports the If-unmodified-since header.

测试

  • The RequestFactory.trace() and Client.trace() methods were implemented, allowing you to create TRACE requests in your tests.
  • The count argument was added to assertTemplateUsed(). This allows you to assert that a template was rendered a specific number of times.
  • The new assertJSONNotEqual() assertion allows you to test that two JSON fragments are not equal.
  • Added options to the test command to preserve the test database (--keepdb), to run the test cases in reverse order (--reverse), and to enable SQL logging for failing tests (--debug-sql).
  • Added the resolver_match attribute to test client responses.
  • Added several settings that allow customization of test tablespace parameters for Oracle: DATAFILE, DATAFILE_TMP, DATAFILE_MAXSIZE and DATAFILE_TMP_MAXSIZE.
  • The override_settings() decorator can now affect the master router in DATABASE_ROUTERS.
  • Added test client support for file uploads with file-like objects.
  • A shared cache is now used when testing with an SQLite in-memory database when using Python 3.4+ and SQLite 3.7.13+. This allows sharing the database between threads.

验证器

  • URLValidator now supports IPv6 addresses, Unicode domains, and URLs containing authentication data.

Backwards incompatible changes in 1.8

警告

In addition to the changes outlined in this section, be sure to review the deprecation plan for any features that have 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.

Some operations on related objects such as add() or direct assignment ran multiple data modifying queries without wrapping them in transactions. To reduce the risk of data corruption, all data modifying methods that affect multiple related objects (i.e. add(), remove(), clear(), and direct assignment) now perform their data modifying queries from within a transaction, provided your database supports transactions.

This has one backwards incompatible side effect, signal handlers triggered from these methods are now executed within the method’s transaction and any exception in a signal handler will prevent the whole operation.

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