Django 1.6 版本发行说明

Django 1.6 版本发行说明

备注

Dedicated to Malcolm Tredinnick

On March 17, 2013, the Django project and the free software community lost a very dear friend and developer.

Malcolm was a long-time contributor to Django, a model community member, a brilliant mind, and a friend. His contributions to Django — and to many other open source projects — are nearly impossible to enumerate. Many on the core Django team had their first patches reviewed by him; his mentorship enriched us. His consideration, patience, and dedication will always be an inspiration to us.

This release of Django is for Malcolm.

-- The Django Developers

2013 年 11 月 6 日

Welcome to Django 1.6!

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.5 or older versions. We’ve also dropped some features, which are detailed in our deprecation plan, and we’ve begun the deprecation process for some features.

Python 兼容性

Django 1.6, like Django 1.5, requires Python 2.6.5 or above. Python 3 is also officially supported. We highly recommend the latest minor release for each supported Python series (2.6.X, 2.7.X, 3.2.X, and 3.3.X).

Django 1.6 will be the final release series to support Python 2.6; beginning with Django 1.7, the minimum supported Python version will be 2.7.

Python 3.4 is not supported, but support will be added in Django 1.7.

What’s new in Django 1.6

Simplified default project and app templates

The default templates used by startproject and startapp have been simplified and modernized. The admin is now enabled by default in new projects; the sites framework no longer is. clickjacking prevention is now on and the database defaults to SQLite.

If the default templates don’t suit your tastes, you can use custom project and app templates.

Improved transaction management

Django’s transaction management was overhauled. Database-level autocommit is now turned on by default. This makes transaction handling more explicit and should improve performance. The existing APIs were deprecated, and new APIs were introduced, as described in the transaction management docs.

Persistent database connections

Django now supports reusing the same database connection for several requests. This avoids the overhead of reestablishing a connection at the beginning of each request. For backwards compatibility, this feature is disabled by default. See 持久连接 for details.

Discovery of tests in any test module

Django 1.6 ships with a new test runner that allows more flexibility in the location of tests. The previous runner (django.test.simple.DjangoTestSuiteRunner) found tests only in the models.py and tests.py modules of a Python package in INSTALLED_APPS.

The new runner (django.test.runner.DiscoverRunner) uses the test discovery features built into unittest2 (the version of unittest in the Python 2.7+ standard library, and bundled with Django). With test discovery, tests can be located in any module whose name matches the pattern test*.py.

In addition, the test labels provided to ./manage.py test to nominate specific tests to run must now be full Python dotted paths (or directory paths), rather than applabel.TestCase.test_method_name pseudo-paths. This allows running tests located anywhere in your codebase, rather than only in INSTALLED_APPS. For more details, see Django 中的测试.

This change is backwards-incompatible; see the backwards-incompatibility notes.

Time zone aware aggregation

The support for time zones introduced in Django 1.4 didn’t work well with QuerySet.dates(): aggregation was always performed in UTC. This limitation was lifted in Django 1.6. Use QuerySet.datetimes() to perform time zone aware aggregation on a DateTimeField.

Support for savepoints in SQLite

Django 1.6 adds support for savepoints in SQLite, with some limitations.

BinaryField model field

A new django.db.models.BinaryField model field allows storage of raw binary data in the database.

GeoDjango form widgets

GeoDjango now provides form fields and widgets for its geo-specialized fields. They are OpenLayers-based by default, but they can be customized to use any other JS framework.

check management command added for verifying compatibility

A check management command was added, enabling you to verify if your current configuration (currently oriented at settings) is compatible with the current version of Django.

Model.save() algorithm changed

The Model.save() method now tries to directly UPDATE the database if the instance has a primary key value. Previously SELECT was performed to determine if UPDATE or INSERT were needed. The new algorithm needs only one query for updating an existing row while the old algorithm needed two. See Model.save() for more details.

In some rare cases the database doesn’t report that a matching row was found when doing an UPDATE. An example is the PostgreSQL ON UPDATE trigger which returns NULL. In such cases it is possible to set django.db.models.Options.select_on_save flag to force saving to use the old algorithm.

次要特性

  • Authentication backends can raise PermissionDenied to immediately fail the authentication chain.
  • The HttpOnly flag can be set on the CSRF cookie with CSRF_COOKIE_HTTPONLY.
  • The assertQuerysetEqual() now checks for undefined order and raises ValueError if undefined order is spotted. The order is seen as undefined if the given QuerySet isn’t ordered and there is more than one ordered value to compare against.
  • Added earliest() for symmetry with latest().
  • In addition to year, month and day, the ORM now supports hour, minute and second lookups.
  • Django now wraps all PEP 249 exceptions.
  • The default widgets for EmailField, URLField, IntegerField, FloatField and DecimalField use the new type attributes available in HTML5 (type='email', type='url', type='number'). Note that due to erratic support of the number input type with localized numbers in current browsers, Django only uses it when numeric fields are not localized.
  • The number argument for lazy plural translations can be provided at translation time rather than at definition time.
  • For custom management commands: Verification of the presence of valid settings in commands that ask for it by using the BaseCommand.can_import_settings internal option is now performed independently from handling of the locale that should be active during the execution of the command. The latter can now be influenced by the new BaseCommand.leave_locale_alone internal option. See 管理命令和本地化 for more details.
  • The success_url of DeletionMixin is now interpolated with its object’s __dict__.
  • HttpResponseRedirect and HttpResponsePermanentRedirect now provide an url attribute (equivalent to the URL the response will redirect to).
  • The MemcachedCache cache backend now uses the latest pickle protocol available.
  • Added SuccessMessageMixin which provides a success_message attribute for FormView based classes.
  • Added the django.db.models.ForeignKey.db_constraint and django.db.models.ManyToManyField.db_constraint options.
  • The jQuery library embedded in the admin has been upgraded to version 1.9.1.
  • Syndication feeds (django.contrib.syndication) can now pass extra context through to feed templates using a new Feed.get_context_data() callback.
  • The admin list columns have a column-<field_name> class in the HTML so the columns header can be styled with CSS, e.g. to set a column width.
  • The isolation level can be customized under PostgreSQL.
  • The blocktrans template tag now respects TEMPLATE_STRING_IF_INVALID for variables not present in the context, just like other template constructs.
  • SimpleLazyObjects will now present more helpful representations in shell debugging situations.
  • Generic GeometryField is now editable with the OpenLayers widget in the admin.
  • The documentation contains a deployment checklist.
  • The diffsettings command gained a --all option.
  • django.forms.fields.Field.__init__ now calls super(), allowing field mixins to implement __init__() methods that will reliably be called.
  • The validate_max parameter was added to BaseFormSet and formset_factory(), and ModelForm and inline versions of the same. The behavior of validation for formsets with max_num was clarified. The previously undocumented behavior that hardened formsets against memory exhaustion attacks was documented, and the undocumented limit of the higher of 1000 or max_num forms was changed so it is always 1000 more than max_num.
  • Added BCryptSHA256PasswordHasher to resolve the password truncation issue with bcrypt.
  • Pillow is now the preferred image manipulation library to use with Django. PIL is pending deprecation (support to be removed in Django 1.8). To upgrade, you should first uninstall PIL, then install Pillow.
  • ModelForm accepts several new Meta options.
    • Fields included in the localized_fields list will be localized (by setting localize on the form field).
    • The labels, help_texts and error_messages options may be used to customize the default fields, see 覆盖默认字段 for details.
  • The choices argument to model fields now accepts an iterable of iterables instead of requiring an iterable of lists or tuples.
  • The reason phrase can be customized in HTTP responses using reason_phrase.
  • When giving the URL of the next page for django.contrib.auth.views.logout(), django.contrib.auth.views.password_reset(), django.contrib.auth.views.password_reset_confirm(), and django.contrib.auth.views.password_change(), you can now pass URL names and they will be resolved.
  • The new dumpdata —pks option specifies the primary keys of objects to dump. This option can only be used with one model.
  • Added QuerySet methods first() and last() which are convenience methods returning the first or last object matching the filters. Returns None if there are no objects matching.
  • View and RedirectView now support HTTP PATCH method.
  • GenericForeignKey now takes an optional for_concrete_model argument, which when set to False allows the field to reference proxy models. The default is True to retain the old behavior.
  • The LocaleMiddleware now stores the active language in session if it is not present there. This prevents loss of language settings after session flush, e.g. logout.
  • SuspiciousOperation has been differentiated into a number of subclasses, and each will log to a matching named logger under the django.security logging hierarchy. Along with this change, a handler400 mechanism and default view are used whenever a SuspiciousOperation reaches the WSGI handler to return an HttpResponseBadRequest.
  • The DoesNotExist exception now includes a message indicating the name of the attribute used for the lookup.
  • The get_or_create() method no longer requires at least one keyword argument.
  • The SimpleTestCase class includes a new assertion helper for testing formset errors: django.test.SimpleTestCase.assertFormsetError().
  • The list of related fields added to a QuerySet by select_related() can be cleared using select_related(None).
  • The get_extra() and get_max_num() methods on InlineModelAdmin may be overridden to customize the extra and maximum number of inline forms.
  • Formsets now have a total_error_count() method.
  • ModelForm fields can now override error messages defined in model fields by using the error_messages argument of a Field’s constructor. To take advantage of this new feature with your custom fields, see the updated recommendation for raising a ValidationError.
  • ModelAdmin now preserves filters on the list view after creating, editing or deleting an object. It’s possible to restore the previous behavior of clearing filters by setting the preserve_filters attribute to False.
  • Added FormMixin.get_prefix (which returns FormMixin.prefix by default) to allow customizing the prefix of the form.
  • Raw queries (Manager.raw() or cursor.execute()) can now use the “pyformat” parameter style, where placeholders in the query are given as '%(name)s' and the parameters are passed as a dictionary rather than a list (except on SQLite). This has long been possible (but not officially supported) on MySQL and PostgreSQL, and is now also available on Oracle.
  • The default iteration count for the PBKDF2 password hasher has been increased by 20%. This backwards compatible change will not affect existing passwords or users who have subclassed django.contrib.auth.hashers.PBKDF2PasswordHasher to change the default value. Passwords will be upgraded to use the new iteration count as necessary.

Backwards incompatible changes in 1.6

警告

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.

New transaction management model

Behavior changes

Database-level autocommit is enabled by default in Django 1.6. While this doesn’t change the general spirit of Django’s transaction management, there are a few backwards-incompatibilities.

Savepoints and assertNumQueries

The changes in transaction management may result in additional statements to create, release or rollback savepoints. This is more likely to happen with SQLite, since it didn’t support savepoints until this release.

If tests using assertNumQueries() fail because of a higher number of queries than expected, check that the extra queries are related to savepoints, and adjust the expected number of queries accordingly.

Autocommit option for PostgreSQL

In previous versions, database-level autocommit was only an option for PostgreSQL, and it was disabled by default. This option is now ignored and can be removed.

New test runner

In order to maintain greater consistency with Python’s unittest module, the new test runner (django.test.runner.DiscoverRunner) does not automatically support some types of tests that were supported by the previous runner:

  • Tests in models.py and tests/__init__.py files will no longer be found and run. Move them to a file whose name begins with test.
  • Doctests will no longer be automatically discovered. To integrate doctests in your test suite, follow the recommendations in the Python documentation.

Django bundles a modified version of the doctest module from the Python standard library (in django.test._doctest) and includes some additional doctest utilities. These utilities are deprecated and will be removed in Django 1.8; doctest suites should be updated to work with the standard library’s doctest module (or converted to unittest-compatible tests).

If you wish to delay updates to your test suite, you can set your TEST_RUNNER setting to django.test.simple.DjangoTestSuiteRunner to fully restore the old test behavior. DjangoTestSuiteRunner is deprecated but will not be removed from Django until version 1.8.

Removal of django.contrib.gis.tests.GeoDjangoTestSuiteRunner GeoDjango custom test runner

This is for developers working on the GeoDjango application itself and related to the item above about changes in the test runners:

The django.contrib.gis.tests.GeoDjangoTestSuiteRunner test runner has been removed and the standalone GeoDjango tests execution setup it implemented isn’t supported anymore. To run the GeoDjango tests simply use the new DiscoverRunner and specify the django.contrib.gis app.

Custom user models in tests

The introduction of the new test runner has also slightly changed the way that test models are imported. As a result, any test that overrides AUTH_USER_MODEL to test behavior with one of Django’s test user models ( django.contrib.auth.tests.custom_user.CustomUser and django.contrib.auth.tests.custom_user.ExtensionUser) must now explicitly import the User model in your test module:

from django.contrib.auth.tests.custom_user import CustomUser

@override_settings(AUTH_USER_MODEL="auth.CustomUser")
class CustomUserFeatureTests(TestCase):
    def test_something(self):
        # Test code here
        ...

This import forces the custom user model to be registered. Without this import, the test will be unable to swap in the custom user model, and you will get an error reporting:

ImproperlyConfigured: AUTH_USER_MODEL refers to model 'auth.CustomUser' that has not been installed

Time zone-aware day, month, and week_day lookups

Django 1.6 introduces time zone support for day, month, and week_day lookups when USE_TZ is True. These lookups were previously performed in UTC regardless of the current time zone.

This requires time zone definitions in the database. If you’re using SQLite, you must install pytz. If you’re using MySQL, you must install pytz and load the time zone tables with mysql_tzinfo_to_sql.

Addition of QuerySet.datetimes()

When the time zone support added in Django 1.4 was active, QuerySet.dates() lookups returned unexpected results, because the aggregation was performed in UTC. To fix this, Django 1.6 introduces a new API, QuerySet.datetimes(). This requires a few changes in your code.

QuerySet.dates() returns date objects

QuerySet.dates() now returns a list of date. It used to return a list of datetime.

QuerySet.datetimes() returns a list of datetime.

QuerySet.dates() no longer usable on DateTimeField

QuerySet.dates() raises an error if it’s used on DateTimeField when time zone support is active. Use QuerySet.datetimes() instead.

date_hierarchy requires time zone definitions

The date_hierarchy feature of the admin now relies on QuerySet.datetimes() when it’s used on a DateTimeField.

This requires time zone definitions in the database when USE_TZ is True. Learn more.

date_list in generic views requires time zone definitions

For the same reason, accessing date_list in the context of a date-based generic view requires time zone definitions in the database when the view is based on a DateTimeField and USE_TZ is True. Learn more.

New lookups may clash with model fields

Django 1.6 introduces hour, minute, and second lookups on DateTimeField. If you had model fields called hour, minute, or second, the new lookups will clash with you field names. Append an explicit exact lookup if this is an issue.

BooleanField no longer defaults to False

When a BooleanField doesn’t have an explicit default, the implicit default value is None. In previous version of Django, it was False, but that didn’t represent accurately the lack of a value.

Code that relies on the default value being False may raise an exception when saving new model instances to the database, because None isn’t an acceptable value for a BooleanField. You should either specify default=False in the field definition, or ensure the field is set to True or False before saving the object.

Translations and comments in templates

Extraction of translations after comments

Extraction of translatable literals from templates with the makemessages command now correctly detects i18n constructs when they are located after a {# / #}-type comment on the same line. E.g.:

{# A comment #}{% trans "This literal was incorrectly ignored. Not anymore" %}

Location of translator comments

模板内对翻译的注释 specified using {# / #} need to be at the end of a line. If they are not, the comments are ignored and makemessages will generate a warning. For example:

{# Translators: This is ignored #}{% trans "Translate me" %}
{{ title }}{# Translators: Extracted and associated with 'Welcome' below #}
<h1>{% trans "Welcome" %}</h1>

Quoting in reverse()

When reversing URLs, Django didn’t apply django.utils.http.urlquote to arguments before interpolating them in URL patterns. This bug is fixed in Django 1.6. If you worked around this bug by applying URL quoting before passing arguments to reverse(), this may result in double-quoting. If this happens, simply remove the URL quoting from your code. You will also have to replace special characters in URLs used in assertRedirects() with their encoded versions.

Storage of IP addresses in the comments app

The comments app now uses a GenericIPAddressField for storing commenters’ IP addresses, to support comments submitted from IPv6 addresses. Until now, it stored them in an IPAddressField, which is only meant to support IPv4. When saving a comment made from an IPv6 address, the address would be silently truncated on MySQL databases, and raise an exception on Oracle. You will need to change the column type in your database to benefit from this change.

For MySQL, execute this query on your project’s database:

ALTER TABLE django_comments MODIFY ip_address VARCHAR(39);

For Oracle, execute this query:

ALTER TABLE DJANGO_COMMENTS MODIFY (ip_address VARCHAR2(39));

If you do not apply this change, the behavior is unchanged: on MySQL, IPv6 addresses are silently truncated; on Oracle, an exception is generated. No database change is needed for SQLite or PostgreSQL databases.

Percent literals in cursor.execute queries

When you are running raw SQL queries through the cursor.execute method, the rule about doubling percent literals (%) inside the query has been unified. Past behavior depended on the database backend. Now, across all backends, you only need to double literal percent characters if you are also providing replacement parameters. For example:

## No parameters, no percent doubling
cursor.execute("SELECT foo FROM bar WHERE baz = '30%'")

## Parameters passed, non-placeholders have to be doubled
cursor.execute("SELECT foo FROM bar WHERE baz = '30%%' and id = %s", [self.id])

SQLite users need to check and update such queries.

Help text of model form fields for ManyToManyField fields

HTML rendering of model form fields corresponding to ManyToManyField model fields used to get the hard-coded sentence:

Hold down “Control”, or “Command” on a Mac, to select more than one.

(or its translation to the active locale) imposed as the help legend shown along them if neither model nor form help_text attributes were specified by the user (or this string was appended to any help_text that was provided).

Since this happened at the model layer, there was no way to prevent the text from appearing in cases where it wasn’t applicable such as form fields that implement user interactions that don’t involve a keyboard and/or a mouse.

Starting with Django 1.6, as an ad-hoc temporary backward-compatibility provision, the logic to add the “Hold down…” sentence has been moved to the model form field layer and modified to add the text only when the associated widget is SelectMultiple or selected subclasses.

The change can affect you in a backward incompatible way if you employ custom model form fields and/or widgets for ManyToManyField model fields whose UIs do rely on the automatic provision of the mentioned hard-coded sentence. These form field implementations need to adapt to the new scenario by providing their own handling of the help_text attribute.

Applications that use Django model form facilities together with Django built-in form fields and widgets aren’t affected but need to be aware of what’s described in Munging of help text of model form fields for ManyToManyField fields below.

QuerySet iteration

The QuerySet iteration was changed to immediately convert all fetched rows to Model objects. In Django 1.5 and earlier the fetched rows were converted to Model objects in chunks of 100.

Existing code will work, but the amount of rows converted to objects might change in certain use cases. Such usages include partially looping over a queryset or any usage which ends up doing __bool__ or __contains__.

Notably most database backends did fetch all the rows in one go already in 1.5.

It is still possible to convert the fetched rows to Model objects lazily by using the iterator() method.

BoundField.label_tag now includes the form’s label_suffix

This is consistent with how methods like Form.as_p and Form.as_ul render labels.

If you manually render label_tag in your templates:

{{ form.my_field.label_tag }}: {{ form.my_field }}

you’ll want to remove the colon (or whatever other separator you may be using) to avoid duplicating it when upgrading to Django 1.6. The following template in Django 1.6 will render identically to the above template in Django 1.5, except that the colon will appear inside the <label> element.

{{ form.my_field.label_tag }} {{ form.my_field }}

will render something like:

<label for="id_my_field">My Field:</label> <input id="id_my_field" type="text" name="my_field" />

If you want to keep the current behavior of rendering label_tag without the label_suffix, instantiate the form label_suffix=''. You can also customize the label_suffix on a per-field basis using the new label_suffix parameter on label_tag().

Admin views _changelist_filters GET parameter

To achieve preserving and restoring list view filters, admin views now pass around the _changelist_filters GET parameter. It’s important that you account for that change if you have custom admin templates or if your tests rely on the previous URLs. If you want to revert to the original behavior you can set the preserve_filters attribute to False.

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