Django 1.10 リリースノート¶
2016年8月1日
Django 1.10 へようこそ!
このリリースノートでは、 バージョン 1.10 の新機能 と、Django 1.9 以前からアップグレードする際に注意が必要な 後方互換性が失われた変更点 について説明します。私たちは、非推奨の期間が終了した いくつかの機能の廃止 を行い、さらに いくつかの機能に対する新しい非推奨期間 を開始しました。
既存のプロジェクトをアップデートするときは、 Django の新しいバージョンへの更新 ガイドに従ってください。
異なる Python への互換性¶
Django 1.9 と同様に、Django 1.10 の動作には Python 2.7、3.4、3.5 のいずれかが必要です。各バージョン系列の最終リリースの Python を使用することを 強く推奨 し、公式には最終リリースしかサポートしません。
Django 1.10 で新しくなったこと¶
PostgreSQL での全文検索¶
django.contrib.postgres には、新しく データベース関数のコレクション が含まれるようになり、全文検索エンジン (full text search engine) が利用可能になりました。リレーショナルデータベース上の複数のフィールドに渡る検索を行い、他の lookup による検索結果と組み合わせ、別の言語設定や重み付けを利用して、検索結果を関連性でランク付けすることができます。
また、トライグラム (trigram) もサポートするようになりました。これを利用するには、trigram_similar lookup、 TrigramSimilarity 、 TrigramDistance 式を使ってください。
新しいスタイルのミドルウェア¶
新しいスタイルのミドルウェアの導入 が行われました。これは、 DEP 0005 に記述されている古いスタイルのミドルウェアのレイヤーに欠けていた、厳密な request/response レイヤーを補うためのものです。この更新の恩恵を受けるには、 古いカスタムミドルウェアを更新する を読んで、 MIDDLEWARE_CLASSES 設定から、新しい MIDDLEWARE 設定に移行してください。
Unicode ユーザー名の公式サポート¶
django.contrib.auth の User モデルは、もともとユーザー名として ASCII 文字しか利用できませんでした。これはよく考えた上での決定ではありませんでしたが、Python 3 を使用しているときには Unicode 文字が必ず利用できます。
ユーザー名検証器 (validator) は、Python 3 のみ、デフォルトで Unicode 文字を受け付けるようになりました。
カスタムの user モデルでは、新しい ASCIIUsernameValidator や UnicodeUsernameValidator を使うこともできます。
マイナーな機能¶
django.contrib.admin¶
サブパス (subpath) で動作しているサイトで
request.META['SCRIPT_NAME']が設定されていた場合、各 admin ページの上部にあるデフォルトの"View site" リンクへの URLとして、/の代わりにこの値を使用します。オブジェクトの追加または編集後に表示される成功メッセージに、オブジェクトの更新フォームへのリンクを表示するようにしました。
すべてのインラインの JavaScript を削除したため、必要な場合に
Content-Security-PolicyHTTP ヘッダーを有効にすることができるようになりました。- The new
InlineModelAdmin.classesattribute allows specifying classes on inline fieldsets. Inlines with acollapseclass 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, of course). This makes it easier to add custom tools in this case. - The
LogEntrymodel now stores change messages in a JSON structure so that the message can be dynamically translated using the current active language. A newLogEntry.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. admin に埋め込まれていた jQuery ライブラリが 2.1.4 から 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. logout()view が “no-cache” ヘッダーを送信するようになりました。これにより、Safari のキャッシュがリダイレクトしてユーザーがログアウトできない問題を避けることができます。オプションの
backend引数をlogin()に追加しました。これにより、認証情報 (credentials) なしでも関数が使用できます。新しい
LOGOUT_REDIRECT_URL設定により、logout()ビューがnext_page引数を取得できない場合にも、リダイレクトを制御できるようになりました。login()ビューに新しいredirect_authenticated_userパラメータが追加されました。これにより、認証済みユーザーをログインページへリダイレクトできるようになります。新しい
AllowAllUsersModelBackendおよびAllowAllUsersRemoteUserBackendは、User.is_activeの値を無視します。一方、ModelBackendおよびRemoteUserBackendは inactive なユーザーを拒否するようになりました。
django.contrib.gis¶
Distance lookups は、distance value パラメータとして、式 (expression) を受け付けるようになりました。
- The new
GEOSGeometry.unary_unionproperty computes the union of all the elements of this geometry. - Added the
GEOSGeometry.covers()binary predicate. - Added the
GDALBand.statistics()method andmeanandstdattributes. - Added support for the
MakeLineaggregate andGeoHashfunction on SpatiaLite. - Added support for the
Difference,Intersection, andSymDifferencefunctions on MySQL. - Added support for instantiating empty GEOS geometries.
- The new
trimandprecisionproperties ofWKTWriterallow controlling output of the fractional part of the coordinates in WKT. - Added the
LineString.closedandMultiLineString.closedproperties. - 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
IsValidandMakeValid, as well as theisvalidlookup, all for PostGIS. This allows filtering and repairing invalid geometries on the database side. - Added raster support for all spatial lookups.
django.contrib.postgres¶
利便性のため、
HStoreFieldは key と value を文字列にキャストするようになりました。
django.contrib.sessions¶
- The
clearsessionsmanagement command now removes file-based sessions.
django.contrib.sites¶
- The
Sitemodel now supports natural keys.
django.contrib.staticfiles¶
- The
statictemplate tag now usesdjango.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 --ignore_patternsoption with a customAppConfig.
キャッシュ¶
ファイルベースのキャッシュバックエンドが highest pickling プロトコルを使用するようになりました。
CSRF¶
デフォルトの
CSRF_FAILURE_VIEWとviews.csrf.csrf_failure()がオプション引数template_nameを取ることができるようになり (デフォルトでは'403_csrf.html'になる)、ページをレンダリングするテンプレートを制御できるようになりました。BREACH 攻撃を防御するため、CSRF プロテクションメカニズムは、リクエストごとにフォームのトークンの値を変更するようになりました (ただし、secret の値は不変のままで、この値は異なるトークンを検証するのに利用します)。
データベースバックエンド¶
- 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 ofFunc.as_sql()for an example.
ファイルストレージ¶
- Storage backends now present a timezone-aware API with new methods
get_accessed_time(),get_created_time(), andget_modified_time(). They return a timezone-awaredatetimeifUSE_TZisTrueand a naivedatetimein the local timezone otherwise. - The new
Storage.generate_filename()method makes it easier to implement custom storages that don’t use theos.pathcalls previously inFileField.
フォーム¶
- Form and widget
Mediais now served usingdjango.contrib.staticfilesif installed. - The
<input>tag rendered byCharFieldnow includes aminlengthattribute if the field has amin_length. - Required form fields now have the
requiredHTML attribute. Set the newForm.use_required_attributeattribute toFalseto disable it. Therequiredattribute isn’t included on forms of formsets because the browser validation may not be correct when adding and deleting formsets.
国際化 (internationalization)¶
- The
i18n_patterns()helper function can now be used in a root URLConf specified usingrequest.urlconf. - By setting the new
prefix_default_languageparameter fori18n_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 nonextparameter inPOSTorGET.- The
JavaScriptCatalogandJSONCatalogclass-based views supersede the deprecatedjavascript_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 fromLOCALE_PATHS.
管理コマンド¶
call_command()now returns the value returned from thecommand.handle()method.- The new
check --fail-leveloption allows specifying the message level that will cause the command to exit with a non-zero status. - The new
makemigrations --checkoption makes the command exit with a non-zero status when model changes without migrations are detected. makemigrationsnow displays the path to the migration files that it generates.- The
shell --interfaceoption now acceptspythonto force use of the “plain” Python interpreter. - The new
shell --commandoption lets you run a command as Django and exit, instead of opening the interactive shell. - Added a warning to
dumpdataif a proxy model is specified (which results in no output) without its concrete parent. - The new
BaseCommand.requires_migrations_checksattribute may be set toTrueif you want your command to print a warning, likerunserverdoes, 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
shellcommand supports tab completion on systems usinglibedit, e.g. Mac OSX. - The
inspectdbcommand 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 theRunSQLandRunPythonoperations 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()andpost_migrate()signals now dispatch their migrationplanandapps.
モデル¶
- Reverse foreign keys from proxy models are now propagated to their
concrete class. The reverse relation attached by a
ForeignKeypointing 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 asForeignKeyandOneToOneFieldthat point to another field. - The
arityclass attribute is added toFunc. This attribute can be used to set the number of arguments the function accepts. - Added
BigAutoFieldwhich acts much like anAutoFieldexcept that it is guaranteed to fit numbers from1to9223372036854775807. QuerySet.in_bulk()may be called without any arguments to return all objects in the queryset.related_query_namenow 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
Castdatabase function. - A proxy model may now inherit multiple proxy models that share a common non-abstract parent class.
- Added
Extractfunctions to extract datetime components as integers, such as year and hour. - Added
Truncfunctions 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_nameandMeta.default_manager_nameoptions allow controlling the_base_managerand_default_manager, respectively.
Request と Response¶
request.userに debug ビューが追加されました。HttpResponseメソッドにreadable()とseekable()を追加して、インスタンスを stream-like オブジェクトにすることで、io.TextIOWrapperでラッピングできるようになりました。CONTENT_TYPEヘッダーをパースして設定されるHttpResponse.content_typeとcontent_params属性を追加しました。request.COOKIESのパーサーが簡略化され、ブラウザの動作に近くなりました。その結果、request.COOKIESには rfc:6265 によれば無効な値を格納してしまう可能性がありますが、document.cookieによって設定することができます。
シリアル化¶
django.core.serializers.json.DjangoJSONEncoderは、よく翻訳可能コンテンツで使用される lazy 文字列をシリアル化できるようになりました。
テンプレート¶
autoescapeオプションがDjangoTemplatesバックエンドとEngineクラスに追加されました。isおよびis not比較演算子がifタグに追加されました。dictsortを使うことで、複数のリストからなるリストを、指定したインデックスの要素を使ってソートできるようになりました。debug()コンテキストプロセッサ (context processor) がデフォルトの alias だけでなく、すべてのデータベースの alias へのクエリを含むようになりました。
テスト¶
- To better catch bugs,
TestCasenow 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 --tagandtest --exclude-tagoptions. - You can now login and use sessions with the test client even if
django.contrib.sessionsis not inINSTALLED_APPS.
URL¶
- 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 takeFORCE_SCRIPT_NAMEinto account when it is set.
バリデータ¶
URLValidatornow 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 optionalallow_negativeboolean parameter, defaulting toFalse, to allow negative integers.
Backwards incompatible changes in 1.10¶
警告
In addition to the changes outlined in this section, be sure to review the 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 storeDurationField.
_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)
PostgreSQL 9.1 に対するサポートの終了¶
2016年9月に PostgreSQL 9.1 に対する upstream のサポートが終了しました。これに伴い、Django 1.10 は PostgreSQL 9.2 を公式にサポートする最低のバージョンに変更しました。
logging モジュール経由の runserver の出力¶
runserver コマンドによる request および response のハンドリングが sys.stderr の代わりに django.server logger に送られるようになりました。Django の logging 設定を無効にしたり自作の logger で上書きした場合にコマンドの出力を表示するには、次のようにして適切な 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 と auth.ExtensionUser テストモデルの削除¶
Django 1.8 でマイグレーションが contrib apps に導入されたため、これらのカスタムな user テストモデルはもう作成されなくなり、テストのコンテキストでは役に立たないものになりました。
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().
non-null な外部キーフィールドに対する null 代入チェックの廃止¶
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.
デフォルトの PASSWORD_HASHERS 設定からの脆弱なパスワードハッシュ生成器の削除¶
Django 0.90 はパスワードを salt なしの MD5 で保存していましたが、Django 0.91 では、salt ありの SHA1 へのサポートと、ユーザーログイン次のパスワードの自動更新に対応しました。Django 1.4 では、PBKDF2 をデフォルトのパスワードハッシュ生成器に追加しています。
古い Django プロジェクトで MD5 または SHA1 (salt 済みのものも含む) でエンコードされたパスワードが使われている場合、現在のハードウェアではいとも簡単にクラックされる可能性があることに注意してください。脆弱なハッシュ生成器を使い続けている可能性を Django のユーザーに周知するため、以下のハッシュ生成器をデフォルトの PASSWORD_HASHERS 設定から削除しました。
'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'
データベース上のハッシュを強化するには、 wrapped password hasher を使用することを検討してください。脆弱でないことがわかっている場合は、プロジェクトの PASSWORD_HASHERS 設定の後ろに必要なハッシュ生成器を追加してください。
次のコードによって、削除されたハッシュ生成器がデータベース内に存在するかどうかをチェックできます。
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() および Field.get_db_prep_lookup() メソッドの削除¶
これらのいずれかのメソッドを実装していたカスタムフィールドがあった場合、それに対するカスタムの lookup を登録できます。たとえば、次のようになります。
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¶
SpatiaLite < 3.0 および GEOS < 3.3 のサポートが終了しました。
後方互換性のための
django.contrib.gis.utils.add_srs_entry()に対するadd_postgis_srs()エイリアスが削除されました。- On Oracle/GIS, the
Areaaggregate function now returns afloatinstead ofdecimal.Decimal. (It’s still wrapped in a measure of square meters.) GEOSGeometryのデフォルトの表現 (WKT の出力) がデフォルトでトリムされるようになりました。つまりPOINT (23.0000000000000000 5.5000000000000000)の代わりにPOINT (23 5.5)を得ることができます。
request body の最大サイズと GET/POST パラメータの数の制限¶
次の新しい2つの設定を使用することで、大きなサイズの request を利用した denial-of-service 攻撃を緩和することができます。
DATA_UPLOAD_MAX_MEMORY_SIZEは request body が持ちうるサイズを制限します。この制限は、ファイルのアップロードには適用されません。DATA_UPLOAD_MAX_NUMBER_FIELDSは、パースされる GET/POST パラメータの数を制限します。
一般的なアプリケーションよりも大きなサイズのフォームの post を受信するアプリケーションの場合は、この値を調整する必要があるかもしれません。
その他¶
QuerySetのrepr()が<QuerySet >にラッピングされるようになりました。これにより、デバッグ時に、単純なリスト表現よりも曖昧さが軽減されます。utils.version.get_version()returns PEP 440 compliant release candidate versions (e.g. ‘1.10rc1’ instead of ‘1.10c1’).- CSRF token values are now required to be strings of 64 alphanumerics; values of 32 alphanumerics, as set by older versions of Django by default, are automatically replaced by strings of 64 characters. Other values are considered invalid. This should only affect developers or users who replace these tokens.
- The
LOGOUT_URLsetting is removed as Django hasn’t made use of it since pre-1.0. If you use it in your project, you can add it to your project’s settings. The default value was'/accounts/logout/'. - Objects with a
close()method such as files and generators passed toHttpResponseare now closed immediately instead of when the WSGI server callsclose()on the response. - A redundant
transaction.atomic()call inQuerySet.update_or_create()is removed. This may affect query counts tested byTransactionTestCase.assertNumQueries(). - Support for
skip_validationinBaseCommand.execute(**options)is removed. Useskip_checks(added in Django 1.7) instead. loaddatanow raises aCommandErrorinstead of showing a warning when the specified fixture file is not found.- Instead of directly accessing the
LogEntry.change_messageattribute, it’s now better to call theLogEntry.get_change_message()method which will provide the message in the current language. - The default error views now raise
TemplateDoesNotExistif a nonexistenttemplate_nameis specified. - The unused
choiceskeyword argument of theSelectandSelectMultiplewidgets’render()method is removed. Thechoicesargument of therender_options()method is also removed, makingselected_choicesthe first argument. - Tests that violate deferrable database constraints will now error when run on a database that supports deferrable constraints.
- Built-in management commands now use indexing of keys in
options, e.g.options['verbosity'], instead ofoptions.get()and no longer perform any type coercion. This could be a problem if you’re calling commands usingCommand.execute()(which bypasses the argument parser that sets a default value) instead ofcall_command(). Instead of callingCommand.execute(), pass the command object as the first argument tocall_command(). ModelBackendandRemoteUserBackendnow reject inactive users. This means that inactive users can’t login and will be logged out if they are switched fromis_active=TruetoFalse. If you need the previous behavior, use the newAllowAllUsersModelBackendorAllowAllUsersRemoteUserBackendinAUTHENTICATION_BACKENDSinstead.- In light of the previous change, the test client’s
login()method no longer always rejects inactive users but instead delegates this decision to the authentication backend.force_login()also delegates the decision to the authentication backend, so if you’re using the default backends, you need to use an active user. django.views.i18n.set_language()may now return a 204 status code for AJAX requests.- The
base_fieldattribute ofRangeFieldis now a type of field, not an instance of a field. If you have created a custom subclass ofRangeField, you should change thebase_fieldattribute. - Middleware classes are now initialized when the server starts rather than during the first request.
- If you override
is_authenticated()oris_anonymous()in a custom user model, you must convert them to attributes or properties as described in the deprecation note. - When using
ModelAdmin.save_as=True, the “Save as new” button now redirects to the change view for the new object instead of to the model’s changelist. If you need the previous behavior, set the newModelAdmin.save_as_continueattribute toFalse. - Required form fields now have the
requiredHTML attribute. Set theForm.use_required_attributeattribute toFalseto disable it. You could also add thenovalidateattribute to<form>if you don’t want browser validation. To disable therequiredattribute on custom widgets, override theWidget.use_required_attribute()method. - The WSGI handler no longer removes content of responses from
HEADrequests or responses with astatus_codeof 100-199, 204, or 304. Most Web servers already implement this behavior. Responses retrieved using the Django test client continue to have these “response fixes” applied. Model.__init__()now receivesdjango.db.models.DEFERREDas the value of deferred fields.- The
Model._deferredattribute is removed as dynamic model classes when usingQuerySet.defer()andonly()is removed. Storage.save()no longer replaces'\'with'/'. This behavior is moved toFileSystemStoragesince this is a storage specific implementation detail. Any Windows user with a custom storage implementation that relies on this behavior will need to implement it in the custom storage’ssave()method.- Private
FileFieldmethodsget_directory_name()andget_filename()are no longer called (and are now deprecated) which is a backwards incompatible change for users overriding those methods on custom fields. To adapt such code, overrideFileField.generate_filename()orStorage.generate_filename()instead. It might be possible to useupload_toalso. - The subject of mail sent by
AdminEmailHandleris no longer truncated at 989 characters. If you were counting on a limited length, truncate the subject yourself. - Private expressions
django.db.models.expressions.DateandDateTimeare removed. The newTruncexpressions provide the same functionality. - The
_base_managerand_default_managerattributes are removed from model instances. They remain accessible on the model class. - Accessing a deleted field on a model instance, e.g. after
del obj.field, reloads the field’s value instead of raisingAttributeError. - If you subclass
AbstractBaseUserand overrideclean(), be sure it callssuper().AbstractBaseUser.normalize_username()is called in a newAbstractBaseUser.clean()method. - Private API
django.forms.models.model_to_dict()returns a queryset rather than a list of primary keys forManyToManyFields . - If
django.contrib.staticfilesis installed, thestatictemplate tag uses thestaticfilesstorage to construct the URL rather than simply joining the value withSTATIC_ROOT. The new approach encodes the URL, which could be backwards-incompatible in cases such as including a fragment in a path, e.g.{% static 'img.svg#fragment' %}, since the#is encoded as%23. To adapt, move the fragment outside the template tag:{% static 'img.svg' %}#fragment. - When
USE_L10NisTrue, localization is now applied for thedateandtimefilters when no format string is specified. TheDATE_FORMATandTIME_FORMATspecifiers from the active locale are used instead of the settings of the same name.
1.10 で非推奨になった機能¶
逆参照外部キー (reverse foreign key) または many-to-many リレーションに対する値の直接代入¶
関連するオブジェクトに直接代入する代わりに、次のように書きます。
>>> new_list = [obj1, obj2, obj3]
>>> e.related_set = new_list
Django 1.9 で追加された set() メソッドを使用すると、次のようになります。
>>> e.related_set.set([obj1, obj2, obj3])
これにより、暗黙の保存による代入によってもたらされる混乱を防ぐことができます。
non-timezone-aware な Storage API¶
古い non-timezone-aware なメソッド accessed_time() 、 created_time() 、および modified_time() が非推奨になり、新しく get_*_time() メソッドに置き換えられました。
サードパーティのストレージバックエンドは新しいメソッドを実装し、古いものを deprecated とマークする必要があります。それまでは、新しい get_*_time() メソッドはベースクラス Storage で古いメソッドから datetime へ必要に応じて変換され、新しいメソッドが実装されるまでは非推奨の警告を出しません。
サードパーティのストレージバックエンドは、古いバージョンの Django のサポートを継続するために 古いメソッドを残しておくこともできます。
django.contrib.gis¶
GEOSGeometryのget_srid()とset_srid()メソッドが非推奨になり、代わりにsridプロパティが導入されました。Pointのget_x()、set_x()、get_y()、set_y()、get_z()、set_z()の各メソッドが非推奨になり、代わりにx、y、zプロパティが導入されました。Pointのget_coords()とset_coords()メソッドが非推奨になり、かわりにtupleプロパティが導入されました。MultiPolygonのcascaded_unionプロパティが非推奨になり、代わりにunary_unionプロパティが導入されました。django.contrib.gis.utils.precision_wkt()関数が非推奨になり、代わりにWKTWriterが導入されました。
CommaSeparatedIntegerField モデルフィールド¶
CommaSeparatedIntegerField が非推奨になり、代わりに validate_comma_separated_integer_list() バリデータ付きの CharField が導入されました。
from django.core.validators import validate_comma_separated_integer_list
from django.db import models
class MyModel(models.Model):
numbers = models.CharField(..., validators=[validate_comma_separated_integer_list])
Oracle を使用している場合、 CharField は CommaSeparatedIntegerField (VARCHAR2) ではなく、異なるデータベースフィールド型 (NVARCHAR2) を使用します。データベースの設定によっては、これは異なるエンドーディングが使用されているということになるため、同じデータに対して異なる長さ (バイト長) となる場合があります。保存された値が VARCHAR2 の 4000 バイトの制限を超えてしまう場合、代わりに TextField (NCLOB) を使用しなければなりません。このとき、フィールドでグループ化するクエリー (たとえば、annotating the model with an aggregation したり、 distinct() を使用するクエリーなど) がある場合には、クエリーを変更する必要があります (to defer the field)。
__search クエリー lookup¶
search lookup は MySQL でのみサポートされていましたが、極めて制限されていた昨日であるため、非推奨になりました。次のようにカスタムの lookup と置き換えてください。
from django.db import models
class Search(models.Lookup):
lookup_name = 'search'
def as_mysql(self, compiler, connection):
lhs, lhs_params = self.process_lhs(compiler, connection)
rhs, rhs_params = self.process_rhs(compiler, connection)
params = lhs_params + rhs_params
return 'MATCH (%s) AGAINST (%s IN BOOLEAN MODE)' % (lhs, rhs), params
models.CharField.register_lookup(Search)
models.TextField.register_lookup(Search)
User.is_authenticated() と User.is_anonymous() をメソッドをして使う¶
AbstractBaseUser と AnonymousUser クラスの is_authenticated() と is_anonymous() メソッドはプロパティに変更されました。Django 2.0 まではメソッドとしても機能しますが、Django ではすべて属性アクセスとして使用されます。
たとえば、 AuthenticationMiddleware を使用して、ユーザーが現在ログインしているかどうかを知りたいときは、次のようにして、
if request.user.is_authenticated:
... # Do something for logged-in users.
else:
... # Do something for anonymous users.
request.user.is_authenticated() メソッドの代わり使用できます。
この変更によって、メソッドの呼び出しをうっかり忘れてしまった場合に情報がリークするのを防ぐことができます。
if request.user.is_authenticated:
return sensitive_information
カスタムのユーザーモデルでこれらのメソッドをオーバーライドした場合には、プロパティまたは属性に変更しなければなりません。
Django は CallableBool オブジェクトを使用しているため、これらの属性をプロパティとメソッドの両方として使用することができます。したがって、非推奨期間が終了するまでは、これらのプロパティを is 演算子を使って比較することはできません。つまり、次のコードは動作しません。
if request.user.is_authenticated is True:
...
The “escape” half of django.utils.safestring¶
The mark_for_escaping() function and the classes it uses: EscapeData,
EscapeBytes, EscapeText, EscapeString, and EscapeUnicode are
deprecated.
As a result, the “lazy” behavior of the escape filter (where it would
always be applied as the last filter no matter where in the filter chain it
appeared) is deprecated. The filter will change to immediately apply
conditional_escape() in Django 2.0.
その他¶
- The
makemigrations --exitoption is deprecated in favor of themakemigrations --checkoption. django.utils.functional.allow_lazy()is deprecated in favor of the newkeep_lazy()function which can be used with a more natural decorator syntax.- The
shell --plainoption is deprecated in favor of-i pythonor--interface python. - Importing from the
django.core.urlresolversmodule is deprecated in favor of its new location,django.urls. - The template
Context.has_key()method is deprecated in favor ofin. - The private attribute
virtual_fieldsofModel._metais deprecated in favor ofprivate_fields. - The private keyword arguments
virtual_onlyinField.contribute_to_class()andvirtualinModel._meta.add_field()are deprecated in favor ofprivate_onlyandprivate, respectively. - The
javascript_catalog()andjson_catalog()views are deprecated in favor of class-based viewsJavaScriptCatalogandJSONCatalog. - In multi-table inheritance, implicit promotion of a
OneToOneFieldto aparent_linkis deprecated. Addparent_link=Trueto such fields. - The private API
Widget._format_value()is made public and renamed toformat_value(). The old name will work through a deprecation period. - Private
FileFieldmethodsget_directory_name()andget_filename()are deprecated in favor of performing this work inStorage.generate_filename()). - Old-style middleware that uses
settings.MIDDLEWARE_CLASSESare deprecated. Adapt old, custom middleware and use the newMIDDLEWAREsetting.
1.10 で削除された機能¶
以下の機能は、非推奨サイクルの終わりに達したため、Django 1.10 で削除されます。詳しくは Features deprecated in 1.8 を見てください。ここには、プロジェクトからこれらの機能を削除する方法についても書かれています。
- Support for calling a
SQLCompilerdirectly as an alias for calling itsquote_name_unless_aliasmethod is removed. - The
cycleandfirstoftemplate tags are removed from thefuturetemplate tag library. django.conf.urls.patterns()is removed.- Support for the
prefixargument todjango.conf.urls.i18n.i18n_patterns()is removed. SimpleTestCase.urlsis removed.- Using an incorrect count of unpacked values in the
fortemplate tag raises an exception rather than failing silently. - The ability to
reverse()URLs using a dotted Python path is removed. - The ability to use a dotted Python path for the
LOGIN_URLandLOGIN_REDIRECT_URLsettings is removed. - Support for
optparseis dropped for custom management commands. - The class
django.core.management.NoArgsCommandis removed. django.core.context_processorsmodule is removed.django.db.models.sql.aggregatesmodule is removed.django.contrib.gis.db.models.sql.aggregatesmodule is removed.- The following methods and properties of
django.db.sql.query.Queryare removed:- Properties:
aggregatesandaggregate_select - Methods:
add_aggregate,set_aggregate_mask, andappend_aggregate_mask.
- Properties:
django.template.resolve_variableis removed.- The following private APIs are removed from
django.db.models.options.Options(Model._meta):get_field_by_name()get_all_field_names()get_fields_with_model()get_concrete_fields_with_model()get_m2m_with_model()get_all_related_objects()get_all_related_objects_with_model()get_all_related_many_to_many_objects()get_all_related_m2m_objects_with_model()
- The
error_messageargument ofdjango.forms.RegexFieldis removed. - The
unordered_listfilter no longer supports old style lists. - Support for string
viewarguments tourl()is removed. - The backward compatible shim to rename
django.forms.Form._has_changed()tohas_changed()is removed. - The
removetagstemplate filter is removed. - The
remove_tags()andstrip_entities()functions indjango.utils.htmlis removed. - The
is_admin_siteargument todjango.contrib.auth.views.password_reset()is removed. django.db.models.field.subclassing.SubfieldBaseis removed.django.utils.checksumsis removed.- The
original_content_type_idattribute ondjango.contrib.admin.helpers.InlineAdminFormis removed. - The backwards compatibility shim to allow
FormMixin.get_form()to be defined with no default value for itsform_classargument is removed. - The following settings are removed, and you must upgrade to the
TEMPLATESsetting:ALLOWED_INCLUDE_ROOTSTEMPLATE_CONTEXT_PROCESSORSTEMPLATE_DEBUGTEMPLATE_DIRSTEMPLATE_LOADERSTEMPLATE_STRING_IF_INVALID
- The backwards compatibility alias
django.template.loader.BaseLoaderis removed. - Django template objects returned by
get_template()andselect_template()no longer accept aContextin theirrender()method. - Template response APIs enforce the use of
dictand backend-dependent template objects instead ofContextandTemplaterespectively. - The
current_appparameter for the following function and classes is removed:django.shortcuts.render()django.template.Context()django.template.RequestContext()django.template.response.TemplateResponse()
- The
dictionaryandcontext_instanceparameters for the following functions are removed:django.shortcuts.render()django.shortcuts.render_to_response()django.template.loader.render_to_string()
- The
dirsparameter for the following functions is removed:django.template.loader.get_template()django.template.loader.select_template()django.shortcuts.render()django.shortcuts.render_to_response()
- Session verification is enabled regardless of whether or not
'django.contrib.auth.middleware.SessionAuthenticationMiddleware'is inMIDDLEWARE_CLASSES.SessionAuthenticationMiddlewareno longer has any purpose and can be removed fromMIDDLEWARE_CLASSES. It’s kept as a stub until Django 2.0 as a courtesy for users who don’t read this note. - Private attribute
django.db.models.Field.relatedis removed. - The
--listoption of themigratemanagement command is removed. - The
ssitemplate tag is removed. - Support for the
=comparison operator in theiftemplate tag is removed. - The backwards compatibility shims to allow
Storage.get_available_name()andStorage.save()to be defined without amax_lengthargument are removed. - Support for the legacy
%(<foo>)ssyntax inModelFormMixin.success_urlis removed. GeoQuerySetaggregate methodscollect(),extent(),extent3d(),make_line(), andunionagg()are removed.- The ability to specify
ContentType.namewhen creating a content type instance is removed. - Support for the old signature of
allow_migrateis removed. - Support for the syntax of
{% cycle %}that uses comma-separated arguments is removed. - The warning that
Signerissued when given an invalid separator is now aValueError.