- Django 1.10 版本发行说明
- Django 1.10 版本发行说明
- Python 兼容性
- Django 1.10 新特性
- 1.10 中的不向后兼容的变更
- 数据库后端 API
- select_related() prohibits non-relational fields for nested relations
- _meta.get_fields() returns consistent reverse fields for proxy models
- AbstractUser.username max_length increased to 150
- Dropped support for PostgreSQL 9.1
- runserver output goes through logging
- auth.CustomUser and auth.ExtensionUser test models were removed
- Apps registry is no longer auto-populated when unpickling models outside of Django
- Removed null assignment check for non-null foreign key fields
- Removed weak password hashers from the default PASSWORD_HASHERS setting
- Field.get_prep_lookup() and Field.get_db_prep_lookup() methods are removed
- django.contrib.gis
- Maximum size of a request body and the number of GET/POST parameters is limited
Django 1.10 版本发行说明
Django 1.10 版本发行说明
2016 年 8 月 1 日
欢迎来到 Django 1.10 版本!
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.9 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 兼容性
Like Django 1.9, Django 1.10 requires Python 2.7, 3.4, or 3.5. We highly recommend and only officially support the latest release of each series.
Django 1.10 新特性
Full text search for PostgreSQL
django.contrib.postgres now includes a collection of database functions to allow the use of the full text search engine. You can search across multiple fields in your relational database, combine the searches with other lookups, use different language configurations and weightings, and rank the results by relevance.
It also now includes trigram support, using the trigram_similar lookup, and the TrigramSimilarity and TrigramDistance expressions.
New-style middleware
A new style of middleware is introduced to solve the lack of strict request/response layering of the old-style of middleware described in DEP 0005. You’ll need to adapt old, custom middleware and switch from the MIDDLEWARE_CLASSES setting to the new MIDDLEWARE setting to take advantage of the improvements.
Official support for Unicode usernames
The User model in django.contrib.auth originally only accepted ASCII letters and numbers in usernames. Although it wasn’t a deliberate choice, Unicode characters have always been accepted when using Python 3.
The username validator now explicitly accepts Unicode characters by default on Python 3 only.
Custom user models may use the new ASCIIUsernameValidator or UnicodeUsernameValidator.
次要特性
django.contrib.admin
- For sites running on a subpath, the default URL for the “View site” link at the top of each admin page will now point to
request.META['SCRIPT_NAME']if set, instead of/. - The success message that appears after adding or editing an object now contains a link to the object’s change form.
- All inline JavaScript is removed so you can enable the
Content-Security-PolicyHTTP header if you wish. - The new InlineModelAdmin.classes attribute allows specifying classes on inline fieldsets. Inlines with a
collapseclass will be initially collapsed and their header will have a small “show” link. - If a user doesn’t have the add permission, the
object-toolsblock on a model’s changelist will now be rendered (without the add button). This makes it easier to add custom tools in this case. - The LogEntry model now stores change messages in a JSON structure so that the message can be dynamically translated using the current active language. A new
LogEntry.get_change_message()method is now the preferred way of retrieving the change message. - Selected objects for fields in
ModelAdmin.raw_id_fieldsnow have a link to object’s change form. - Added “No date” and “Has date” choices for
DateFieldListFilterif the field is nullable. - The jQuery library embedded in the admin is upgraded from version 2.1.4 to 2.2.3.
django.contrib.auth
- Added support for the Argon2 password hash. It’s recommended over PBKDF2, however, it’s not the default as it requires a third-party library.
- The default iteration count for the PBKDF2 password hasher has been increased by 25%. This backwards compatible change will not affect users who have subclassed
django.contrib.auth.hashers.PBKDF2PasswordHasherto change the default value. - The
django.contrib.auth.views.logout()view sends “no-cache” headers to prevent an issue where Safari caches redirects and prevents a user from being able to log out. - Added the optional
backendargument to django.contrib.auth.login() to allow using it without credentials. - The new LOGOUT_REDIRECT_URL setting controls the redirect of the
django.contrib.auth.views.logout()view, if the view doesn’t get anext_pageargument. - The new
redirect_authenticated_userparameter for thedjango.contrib.auth.views.login()view allows redirecting authenticated users visiting the login page. - The new AllowAllUsersModelBackend and AllowAllUsersRemoteUserBackend ignore the value of
User.is_active, while ModelBackend and RemoteUserBackend now reject inactive users.
django.contrib.gis
- Distance lookups now accept expressions as the distance value parameter.
- The new GEOSGeometry.unary_union property computes the union of all the elements of this geometry.
- Added the GEOSGeometry.covers() binary predicate.
- Added the GDALBand.statistics() method and mean and std attributes.
- Added support for the MakeLine aggregate and GeoHash function on SpatiaLite.
- Added support for the Difference, Intersection, and SymDifference functions on MySQL.
- Added support for instantiating empty GEOS geometries.
- The new trim and precision properties of WKTWriter allow controlling output of the fractional part of the coordinates in WKT.
- Added the LineString.closed and MultiLineString.closed properties.
- The GeoJSON serializer now outputs the primary key of objects in the
propertiesdictionary if specific fields aren’t specified. - The ability to replicate input data on the GDALBand.data() method was added. Band data can now be updated with repeated values efficiently.
- Added database functions IsValid and MakeValid, as well as the isvalid lookup, all for PostGIS. This allows filtering and repairing invalid geometries on the database side.
- Added raster support for all spatial lookups.
django.contrib.postgres
- For convenience, HStoreField now casts its keys and values to strings.
django.contrib.sessions
- The clearsessions management command now removes file-based sessions.
django.contrib.sites
- The Site model now supports natural keys.
django.contrib.staticfiles
- The static template tag now uses
django.contrib.staticfilesif it’s inINSTALLED_APPS. This is especially useful for third-party apps which can now always use{% load static %}(instead of{% load staticfiles %}or{% load static from staticfiles %}) and not worry about whether or not thestaticfilesapp is installed. - You can more easily customize the
collectstatic --ignoreoption with a customAppConfig.
缓存
- The file-based cache backend now uses the highest pickling protocol.
CSRF
- The default CSRF_FAILURE_VIEW,
views.csrf.csrf_failure()now accepts an optionaltemplate_nameparameter, defaulting to'403_csrf.html', to control the template used to render the page. - To protect against BREACH attacks, the CSRF protection mechanism now changes the form token value on every request (while keeping an invariant secret which can be used to validate the different tokens).
数据库后端
- Temporal data subtraction was unified on all backends.
- If the database supports it, backends can set
DatabaseFeatures.can_return_ids_from_bulk_insert=Trueand implementDatabaseOperations.fetch_returned_insert_ids()to set primary keys on objects created usingQuerySet.bulk_create(). - Added keyword arguments to the
as_sql()methods of various expressions (Func,When,Case, andOrderBy) to allow database backends to customize them without mutatingself, which isn’t safe when using different database backends. See thearg_joinerand**extra_contextparameters of Func.as_sql() for an example.
文件存储
- Storage backends now present a timezone-aware API with new methods get_accessed_time(), get_created_time(), and get_modified_time(). They return a timezone-aware
datetimeif USE_TZ isTrueand a naivedatetimein the local timezone otherwise. - The new Storage.generate_filename() method makes it easier to implement custom storages that don’t use the
os.pathcalls previously in FileField.
表单
- Form and widget
Mediais now served using django.contrib.staticfiles if installed. - The
<input>tag rendered by CharField now includes aminlengthattribute if the field has amin_length. - Required form fields now have the
requiredHTML attribute. Set the new Form.use_required_attribute attribute toFalseto disable it. Therequiredattribute isn’t included on forms of formsets because the browser validation may not be correct when adding and deleting formsets.
通用视图
- The View class can now be imported from
django.views.
国际化
- The i18n_patterns() helper function can now be used in a root URLConf specified using request.urlconf.
- By setting the new
prefix_default_languageparameter for i18n_patterns() toFalse, you can allow accessing the default language without a URL prefix. - set_language() now returns a 204 status code (No Content) for AJAX requests when there is no
nextparameter inPOSTorGET. - The JavaScriptCatalog and JSONCatalog class-based views supersede the deprecated
javascript_catalog()andjson_catalog()function-based views. The new views are almost equivalent to the old ones except that by default the new views collect all JavaScript strings in thedjangojstranslation domain from all installed apps rather than only the JavaScript strings from LOCALE_PATHS.
管理命令
- call_command() now returns the value returned from the
command.handle()method. - The new check —fail-level option allows specifying the message level that will cause the command to exit with a non-zero status.
- The new makemigrations —check option makes the command exit with a non-zero status when model changes without migrations are detected.
- makemigrations now displays the path to the migration files that it generates.
- The shell —interface option now accepts
pythonto force use of the “plain” Python interpreter. - The new shell —command option lets you run a command as Django and exit, instead of opening the interactive shell.
- Added a warning to dumpdata if a proxy model is specified (which results in no output) without its concrete parent.
- The new BaseCommand.requires_migrations_checks attribute may be set to
Trueif you want your command to print a warning, like runserver does, if the set of migrations on disk don’t match the migrations in the database. - To assist with testing, call_command() now accepts a command object as the first argument.
- The shell command supports tab completion on systems using
libedit, e.g. macOS. - The inspectdb command lets you choose what tables should be inspected by specifying their names as arguments.
迁移
- Added support for serialization of
enum.Enumobjects. - Added the
elidableargument to the RunSQL and RunPython operations to allow them to be removed when squashing migrations. - Added support for non-atomic migrations by setting the
atomicattribute on aMigration. - The
migrateandmakemigrationscommands now check for a consistent migration history. If they find some unapplied dependencies of an applied migration,InconsistentMigrationHistoryis raised. - The pre_migrate() and post_migrate() signals now dispatch their migration
planandapps.
模型
- Reverse foreign keys from proxy models are now propagated to their concrete class. The reverse relation attached by a ForeignKey pointing to a proxy model is now accessible as a descriptor on the proxied model class and may be referenced in queryset filtering.
- The new Field.rel_db_type() method returns the database column data type for fields such as
ForeignKeyandOneToOneFieldthat point to another field. - The arity class attribute is added to Func. This attribute can be used to set the number of arguments the function accepts.
- Added BigAutoField which acts much like an AutoField except that it is guaranteed to fit numbers from
1to9223372036854775807. - QuerySet.in_bulk() may be called without any arguments to return all objects in the queryset.
- related_query_name now supports app label and class interpolation using the
'%(app_label)s'and'%(class)s'strings. - Allowed overriding model fields inherited from abstract base classes.
- The prefetch_related_objects() function is now a public API.
- QuerySet.bulk_create() sets the primary key on objects when using PostgreSQL.
- Added the Cast database function.
- A proxy model may now inherit multiple proxy models that share a common non-abstract parent class.
- Added Extract functions to extract datetime components as integers, such as year and hour.
- Added Trunc functions to truncate a date or datetime to a significant component. They enable queries like sales-per-day or sales-per-hour.
Model.__init__()now sets values of virtual fields from its keyword arguments.- The new Meta.base_manager_name and Meta.default_manager_name options allow controlling the _base_manager and _default_manager, respectively.
请求和响应
- Added
request.userto the debug view. - Added HttpResponse methods readable() and seekable() to make an instance a stream-like object and allow wrapping it with io.TextIOWrapper.
- Added the HttpRequest.content_type and content_params attributes which are parsed from the
CONTENT_TYPEheader. - The parser for
request.COOKIESis simplified to better match the behavior of browsers.request.COOKIESmay now contain cookies that are invalid according to RFC 6265 but are possible to set viadocument.cookie.
序列化
- The
django.core.serializers.json.DjangoJSONEncodernow knows how to serialize lazy strings, typically used for translatable content.
模板
- Added the
autoescapeoption to the DjangoTemplates backend and the Engine class. - Added the
isandis notcomparison operators to the if tag. - Allowed dictsort to order a list of lists by an element at a specified index.
- The debug() context processor contains queries for all database aliases instead of only the default alias.
- Added relative path support for string arguments of the extends and include template tags.
测试
- To better catch bugs, TestCase now checks deferrable database constraints at the end of each test.
- Tests and test cases can be marked with tags and run selectively with the new test —tag and test —exclude-tag options.
- You can now login and use sessions with the test client even if django.contrib.sessions is not in INSTALLED_APPS.
URLs
- An addition in django.setup() allows URL resolving that happens outside of the request/response cycle (e.g. in management commands and standalone scripts) to take FORCE_SCRIPT_NAME into account when it is set.
验证器
- URLValidator now limits the length of domain name labels to 63 characters and the total length of domain names to 253 characters per RFC 1034.
- int_list_validator() now accepts an optional
allow_negativeboolean parameter, defaulting toFalse, to allow negative integers.
1.10 中的不向后兼容的变更
警告
In addition to the changes outlined in this section, be sure to review the Features removed in 1.10 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
- GIS’s
AreaFielduses an unspecified underlying numeric type that could in practice be any numeric Python type.decimal.Decimalvalues retrieved from the database are now converted tofloatto make it easier to combine them with values used by the GIS libraries. - In order to enable temporal subtraction you must set the
supports_temporal_subtractiondatabase feature flag toTrueand implement theDatabaseOperations.subtract_temporals()method. This method should return the SQL and parameters required to compute the difference in microseconds between thelhsandrhsarguments in the datatype used to store DurationField.
select_related() prohibits non-relational fields for nested relations
Django 1.8 added validation for non-relational fields in select_related():
>>> Book.objects.select_related("title")
Traceback (most recent call last):
...
FieldError: Non-relational field given in select_related: 'title'
But it didn’t prohibit nested non-relation fields as it does now:
>>> Book.objects.select_related("author__name")
Traceback (most recent call last):
...
FieldError: Non-relational field given in select_related: 'name'
_meta.get_fields() returns consistent reverse fields for proxy models
Before Django 1.10, the get_fields() method returned different reverse fields when called on a proxy model compared to its proxied concrete class. This inconsistency was fixed by returning the full set of fields pointing to a concrete class or one of its proxies in both cases.
AbstractUser.username max_length increased to 150
A migration for django.contrib.auth.models.User.username is included. If you have a custom user model inheriting from AbstractUser, you’ll need to generate and apply a database migration for your user model.
We considered an increase to 254 characters to more easily allow the use of email addresses (which are limited to 254 characters) as usernames but rejected it due to a MySQL limitation. When using the utf8mb4 encoding (recommended for proper Unicode support), MySQL can only create unique indexes with 191 characters by default. Therefore, if you need a longer length, please use a custom user model.
If you want to preserve the 30 character limit for usernames, use a custom form when creating a user or changing usernames:
from django.contrib.auth.forms import UserCreationForm
class MyUserCreationForm(UserCreationForm):
username = forms.CharField(
max_length=30,
help_text="Required. 30 characters or fewer. Letters, digits and @/./+/-/_ only.",
)
If you wish to keep this restriction in the admin, set UserAdmin.add_form to use this form:
from django.contrib.auth.admin import UserAdmin as BaseUserAdmin
from django.contrib.auth.models import User
class UserAdmin(BaseUserAdmin):
add_form = MyUserCreationForm
admin.site.unregister(User)
admin.site.register(User, UserAdmin)
Dropped support for PostgreSQL 9.1
Upstream support for PostgreSQL 9.1 ends in September 2016. As a consequence, Django 1.10 sets PostgreSQL 9.2 as the minimum version it officially supports.
runserver output goes through logging
Request and response handling of the runserver command is sent to the django.server logger instead of to sys.stderr. If you disable Django’s logging configuration or override it with your own, you’ll need to add the appropriate logging configuration if you want to see that output:
LOGGING = {
# ...
"formatters": {
"django.server": {
"()": "django.utils.log.ServerFormatter",
"format": "[%(server_time)s] %(message)s",
}
},
"handlers": {
"django.server": {
"level": "INFO",
"class": "logging.StreamHandler",
"formatter": "django.server",
},
},
"loggers": {
"django.server": {
"handlers": ["django.server"],
"level": "INFO",
"propagate": False,
}
},
}
auth.CustomUser and auth.ExtensionUser test models were removed
Since the introduction of migrations for the contrib apps in Django 1.8, the tables of these custom user test models were not created anymore making them unusable in a testing context.
Apps registry is no longer auto-populated when unpickling models outside of Django
The apps registry is no longer auto-populated when unpickling models. This was added in Django 1.7.2 as an attempt to allow unpickling models outside of Django, such as in an RQ worker, without calling django.setup(), but it creates the possibility of a deadlock. To adapt your code in the case of RQ, you can provide your own worker script that calls django.setup().
Removed null assignment check for non-null foreign key fields
In older versions, assigning None to a non-nullable ForeignKey or OneToOneField raised ValueError('Cannot assign None: "model.field" does not allow null values.'). For consistency with other model fields which don’t have a similar check, this check is removed.
Removed weak password hashers from the default PASSWORD_HASHERS setting
Django 0.90 stored passwords as unsalted MD5. Django 0.91 added support for salted SHA1 with automatic upgrade of passwords when a user logs in. Django 1.4 added PBKDF2 as the default password hasher.
If you have an old Django project with MD5 or SHA1 (even salted) encoded passwords, be aware that these can be cracked fairly easily with today’s hardware. To make Django users acknowledge continued use of weak hashers, the following hashers are removed from the default PASSWORD_HASHERS setting:
"django.contrib.auth.hashers.SHA1PasswordHasher"
"django.contrib.auth.hashers.MD5PasswordHasher"
"django.contrib.auth.hashers.UnsaltedSHA1PasswordHasher"
"django.contrib.auth.hashers.UnsaltedMD5PasswordHasher"
"django.contrib.auth.hashers.CryptPasswordHasher"
Consider using a wrapped password hasher to strengthen the hashes in your database. If that’s not feasible, add the PASSWORD_HASHERS setting to your project and add back any hashers that you need.
You can check if your database has any of the removed hashers like this:
from django.contrib.auth import get_user_model
User = get_user_model()
## Unsalted MD5/SHA1:
User.objects.filter(password__startswith="md5$$")
User.objects.filter(password__startswith="sha1$$")
## Salted MD5/SHA1:
User.objects.filter(password__startswith="md5$").exclude(password__startswith="md5$$")
User.objects.filter(password__startswith="sha1$").exclude(password__startswith="sha1$$")
## Crypt hasher:
User.objects.filter(password__startswith="crypt$$")
from django.db.models import CharField
from django.db.models.functions import Length
CharField.register_lookup(Length)
## Unsalted MD5 passwords might not have an 'md5$$' prefix:
User.objects.filter(password__length=32)
Field.get_prep_lookup() and Field.get_db_prep_lookup() methods are removed
If you have a custom field that implements either of these methods, register a custom lookup for it. For example:
from django.db.models import Field
from django.db.models.lookups import Exact
class MyField(Field):
...
class MyFieldExact(Exact):
def get_prep_lookup(self):
# do_custom_stuff_for_myfield
...
MyField.register_lookup(MyFieldExact)
django.contrib.gis
- Support for SpatiaLite < 3.0 and GEOS < 3.3 is dropped.
- The
add_postgis_srs()backwards compatibility alias fordjango.contrib.gis.utils.add_srs_entry()is removed. - On Oracle/GIS, the Area aggregate function now returns a
floatinstead ofdecimal.Decimal. (It’s still wrapped in a measure of square meters.) - The default GEOSGeometry representation (WKT output) is trimmed by default. That is, instead of
POINT (23.0000000000000000 5.5000000000000000), you’ll getPOINT (23 5.5).
Maximum size of a request body and the number of GET/POST parameters is limited
Two new settings help mitigate denial-of-service attacks via large requests:
- DATA_UPLOAD_MAX_MEMORY_SIZE limits the size that a request body may be. File uploads don’t count toward this limit.
- DATA_UPLOAD_MAX_NUMBER_FIELDS limits the number of GET/POST parameters that are parsed.
Applications that receive unusually large form posts may need to tune these settings.
(本文超出站点单文档体积上限,已按小节截断)
