Django 1.11 リリースノート¶
April 4, 2017
Django 1.11 へようこそ!
このリリースノートでは、Django 1.10 および過去のバージョンからアップグレードする際に知っておくべきいくつかの 後方互換性のない変更 に加え、新機能 を説明しています。いくつかの機能に対する廃止プロセスを開始しました。
既存のプロジェクトをアップデートするときは、 Django の新しいバージョンへの更新 ガイドに従ってください。
Django 1.11 は、長期サポートリリース として設計されています。リリースから最低3年間はセキュリティアップデートを受けます。以前の LTS および Django 1.8 に対するサポートは2018年4月に終了します。
異なる Python への互換性¶
Django 1.11 は Python 2.7、3.4、3.5、3.6 のいずれかを必要とします。Django 1.11 は Python 3.6 をサポートする最初のリリースです。各シリーズの最後のリリースを 強く推奨する とともに、唯一公式にサポートします。
The Django 1.11.x series is the last to support Python 2. The next major release, Django 2.0, will only support Python 3.4+.
廃止予定警告はデフォルトでは表示されなくなりました。¶
Django の過去のバージョンとは異なり、Django 自体の廃止予定警告はデフォルトでは非表示となりました。これは Python のデフォルト動作と同じです。
これによって、サードパーティアプリが、廃止予定警告を回避するためのコードを追加することなく、Django 1.11 LTS と Django 1.8 LTS の両方をサポートできるようになります。
Django 2.0 のリリースを控えているため、サードパーティアプリの開発者は 1.11 以前のバージョンの Django へのサポートを終えるよう推奨します。このとき、python -Wd を使ったパッケージテストを実行できるようにして、廃止予定警告を表示します。廃止予定警告を作り終えたら、アプリケーションは Django 2.0 と互換可能となります。
What’s new in Django 1.11¶
クラスベースモデルのインデックス¶
新しい django.db.models.indexes モジュールはデータベースインデックスの作成を簡単にするクラスを含んでいます。インデックスは Meta.indexes オプションを使ってモデルに追加されます。
The Index class creates a b-tree index, as if you
used db_index on the model field or
index_together on the model Meta class.
It can be subclassed to support different index types, such as
GinIndex. It also allows defining the
order (ASC/DESC) for the columns of the index.
テンプレートベースのウィジェット表示¶
ウィジェットのカスタマイズを簡単にするため、フォームウィジェットの表示が Python 内ではなくテンプレートシステムを使って行われるようになりました。The form rendering API を参照してください。
いくつかの 後方互換性のない変更 のため、実装済みのカスタムウィジェットを調整する必要があるかもしれません。
Subquery 表現¶
新たな Subquery と Exists データベース表現によって、明示的なサブクエリを作成することができます。サブクエリは、OuterRef を使って外部のクエリセットからフィールドを参照することができます。
マイナーな機能¶
django.contrib.admin¶
ModelAdmin.date_hierarchyはリレーションシップを通じてフィールドを参照できるようになりました。- 新たな
ModelAdmin.get_exclude()フックによって、リクエストやモデルインスタンスに基づいた除外フィールドを指定できます。 popup_response.htmlテンプレートが、アプリケーションごと、モデルごと、もしくはセッティングModelAdmin.popup_response_template属性によってオーバーライドできるようになりました。
django.contrib.auth¶
- PBKDF2 パスワードハッシュに対するデフォルトのイテレーションカウントが 20% 増加しました。
LoginViewとLogoutViewクラスベースビューが、廃止されるlogin()とlogout()関数ベースビューの後継となりました。PasswordChangeView、PasswordChangeDoneView、PasswordResetView、PasswordResetDoneView、PasswordResetConfirmView、PasswordResetCompleteViewクラスベースビューが、廃止されるpassword_change()、password_change_done()、password_reset()、password_reset_done()、password_reset_confirm()、password_reset_complete()関数ビューの後継となりました。PasswordResetConfirmViewの新しいpost_reset_login属性によって、パスワードリセットが成功した後に自動的にログインできるようになりました。複数のAUTHENTICATION_BACKENDSを設定している場合、post_reset_login_backend属性を使ってどれを使うか選択してください。- HTTP リファラヘッダを通じてパスワードリセットトークンが漏れる可能性を防ぐため (例えば、リセットページが他のドメインにホストされた CSS や JavaScript への参照を含む場合)、
PasswordResetConfirmView(廃止されるpassword_reset_confirm()関数ベースビューではありません) セッションにトークンを保持し、自身にリダイレクトして URL 内のトークンなしでユーザへのパスワード変更フォームを送信します。 update_session_auth_hash()がセッションキーをローテーションさせるようになり、パスワード変更が盗聴されたセッションクッキーを無効化できるようになりました。LoginViewとLogoutViewの新しいsuccess_url_allowed_hosts属性によって、ログインおよびログアウト後のリダイレクトに対して安全なホストのセットを指定できるようになりました。- パスワードのバリデータ
help_textがUserCreationFormに追加されました。 HttpRequestがauthenticate()に渡されるようになりました。これは、request属性を受け入れる場合にリクエストを認証バックエンドに順番に渡します。user_login_failed()シグナルがrequest属性を受け取るようになりました。PasswordResetFormは'email'ではない名前の E メールフィールドを使うカスタムユーザーモデルをサポートします。CustomUser.EMAIL_FIELDをフィールドの名前にセットしてください。- モデルを定義するモジュール内においても、
get_user_model()をインポート時に呼ぶことができるようになりました。
django.contrib.contenttypes¶
- When stale content types are detected in the
remove_stale_contenttypescommand, there’s now a list of related objects such asauth.Permissions that will also be deleted. Previously, only the content types were listed (and this prompt was aftermigraterather than in a separate command).
django.contrib.gis¶
- 新たな
GEOSGeometry.from_gml()とOGRGeometry.from_gml()メソッドによって、GML から幾何学的配置を作成できるようになりました。 - Added support for the
dwithinlookup on SpatiaLite. - The
Areafunction,Distancefunction, and distance lookups now work with geodetic coordinates on SpatiaLite. - The OpenLayers-based form widgets now use
OpenLayers.jsfromhttps://cdnjs.cloudflare.comwhich is more suitable for production use than the the oldhttp://openlayers.orgsource. They are also updated to use OpenLayers 3. - PostGIS migrations can now change field dimensions.
- Added the ability to pass the size, shape, and offset parameter when
creating
GDALRasterobjects. - Added SpatiaLite support for the
IsValidfunction,MakeValidfunction, andisvalidlookup. - Added Oracle support for the
AsGMLfunction,BoundingCirclefunction,IsValidfunction, andisvalidlookup.
django.contrib.postgres¶
- The new
distinctargument forStringAggdetermines if concatenated values will be distinct. - The new
GinIndexandBrinIndexclasses allow creatingGINandBRINindexes in the database. JSONFieldaccepts a newencoderparameter to specify a custom class to encode data types not supported by the standard encoder.- The new
CITextmixin andCITextExtensionmigration operation allow using PostgreSQL’scitextextension for case-insensitive lookups. Three fields are provided:CICharField,CIEmailField, andCITextField. - The new
JSONBAggallows aggregating values as a JSON array. - The
HStoreField(model field) andHStoreField(form field) allow storing null values.
キャッシュ¶
- Memcached backends now pass the contents of
OPTIONSas keyword arguments to the client constructors, allowing for more advanced control of client behavior. See the cache arguments documentation for examples. - Memcached backends now allow defining multiple servers as a comma-delimited
string in
LOCATION, for convenience with third-party services that use such strings in environment variables.
CSRF¶
- Added the
CSRF_USE_SESSIONSsetting to allow storing the CSRF token in the user’s session rather than in a cookie.
データベースバックエンド¶
- Added the
skip_lockedargument toQuerySet.select_for_update()on PostgreSQL 9.5+ and Oracle to execute queries withFOR UPDATE SKIP LOCKED. - Added the
TEST['TEMPLATE']setting to let PostgreSQL users specify a template for creating the test database. QuerySet.iterator()now uses server-side cursors on PostgreSQL. This feature transfers some of the worker memory load (used to hold query results) to the database and might increase database memory usage.- Added MySQL support for the
'isolation_level'option inOPTIONSto allow specifying the transaction isolation level. To avoid possible data loss, it’s recommended to switch from MySQL’s default level, repeatable read, to read committed. - Added support for
cx_Oracle5.3.
E メール¶
EMAIL_USE_LOCALTIME設定が追加され、SMTP 日付ヘッダを UTC ではなくローカルタイムゾーンで送信できるようになりました。- UTF-8 にデコードできないバイナリコンテンツが
text/*添付ファイルに指定されているとき、EmailMessage.attach()とattach_file()が MIME タイプapplication/octet-streamにフォールバックするようになりました。
ファイルストレージ¶
io.TextIOWrapperでラップできるように、Fileにreadable()、writable()、seekable()メソッドが追加されました。
フォーム¶
- 新たな
CharField.empty_value属性によって Python の値を指定して 「空 (empty)」 を表現できるようになりました。 - 新たな
Form.get_initial_for_field()メソッドは、フォームフィールドに対する初期データを返します。
国際化 (internationalization)¶
- 数値の書式および
NUMBER_GROUPING設定が単一ではない桁グルーピングをサポートするようになりました。
管理コマンド¶
- 新たな
loaddata --excludeオプションによって、フィクスチャからデータを読み込んでいる間にモデルとアプリケーションを除外することができるようになりました。 - 新たな
diffsettings --defaultオプションによって、Django のデフォルトの設定以外の設定モジュールを指定し、対比できるようになりました。 app_label属性がshowmigrations --planアウトプットを制限するようになりました。
マイグレーション¶
uuid.UUIDオブジェクトのシリアル化に対するサポートを追加しました。
モデル¶
QuerySet.update_or_create()とget_or_create()のdefaults属性で呼び出し可能な値に対するサポートが追加されました。ImageFieldnow has a defaultvalidate_image_file_extensionvalidator. (This validator moved to the form field in Django 1.11.2.)Trunc関数に時刻を丸めるサポートを追加しました。ExtractWeek関数を追加してDateFieldとDateTimeFieldから週を抽出できるようにし、weekルックアップを通じて公開しました。TruncTime関数を追加してDateTimeFieldを時刻コンポーネントに丸められるようにし、timeを通じて公開しました。QuerySet.values()とvalues_list()の表現へのサポートを追加しました。rangeのような複数属性を取るルックアップでのクエリ表現へのサポートを追加しました。FileFieldでunique=Trueオプションを使用できるようになりました。nulls_firstとnulls_lastパラメータをExpression.asc()とdesc()に追加し、null 値の順序をコントロールできるようにしました。- 新たな
F表現bitleftshift()とbitrightshift()メソッドによって、ビットワイズシフトオペレーション ができるようになりました。 QuerySet.union()、intersection()、difference()を追加しました。
Request と Response¶
QueryDict.fromkeys()を追加しました。CommonMiddlewareが 非ストリーミングレスポンスに対してContent-Lengthレスポンスヘッダをセットするようになりました。- Added the
SECURE_HSTS_PRELOADsetting to allow appending thepreloaddirective to theStrict-Transport-Securityheader. ConditionalGetMiddlewarenow adds theETagheader to responses.
シリアル化¶
- The new
django.core.serializers.base.Serializer.stream_classattribute allows subclasses to customize the default stream. - The encoder used by the JSON serializer
can now be customized by passing a
clskeyword argument to theserializers.serialize()function. DjangoJSONEncodernow serializestimedeltaobjects (used byDurationField).
テンプレート¶
mark_safe()can now be used as a decorator.- The
Jinja2template backend now supports context processors by setting the'context_processors'option inOPTIONS. - The
regrouptag now returnsnamedtuples instead of dictionaries so you can unpack the group object directly in a loop, e.g.{% for grouper, list in regrouped %}. - Added a
resetcycletemplate tag to allow resetting the sequence of thecycletemplate tag. - You can now specify specific directories for a particular
filesystem.Loader.
テスト¶
- Added
DiscoverRunner.get_test_runner_kwargs()to allow customizing the keyword arguments passed to the test runner. - Added the
test --debug-modeoption to help troubleshoot test failures by setting theDEBUGsetting toTrue. - The new
django.test.utils.setup_databases()(moved fromdjango.test.runner) andteardown_databases()functions make it easier to build custom test runners. - Added support for
unittest.TestCase.subTest()’s when using thetest --paralleloption. DiscoverRunnernow runs the system checks at the start of a test run. Override theDiscoverRunner.run_checks()method if you want to disable that.
バリデータ¶
- ファイル拡張子を検証する
FileExtensionValidatorと、 画像ファイルを検証するvalidate_image_file_extensionを追加しました。
1.11 における後方互換性のない変更¶
django.contrib.gis¶
- To simplify the codebase and because it’s easier to install than when
contrib.giswas first released, GDAL is now a required dependency for GeoDjango. In older versions, it’s only required for SQLite. contrib.gis.mapsis removed as it interfaces with a retired version of the Google Maps API and seems to be unmaintained. If you’re using it, let us know.- The
GEOSGeometryequality operator now also compares SRID. - The OpenLayers-based form widgets now use OpenLayers 3, and the
gis/openlayers.htmlandgis/openlayers-osm.htmltemplates have been updated. Check your project if you subclass these widgets or extend the templates. Also, the new widgets work a bit differently than the old ones. Instead of using a toolbar in the widget, you click to draw, click and drag to move the map, and click and drag a point/vertex/corner to move it. - Support for SpatiaLite < 4.0 is dropped.
- Support for GDAL 1.7 and 1.8 is dropped.
- The widgets in
contrib.gis.forms.widgetsand the admin’sOpenLayersWidgetuse the form rendering API rather thanloader.render_to_string(). If you’re using a custom widget template, you’ll need to be sure your form renderer can locate it. For example, you could use theTemplatesSettingrenderer.
django.contrib.staticfiles¶
collectstaticmay now fail during post-processing when using a hashed static files storage if a reference loop exists (e.g.'foo.css'references'bar.css'which itself references'foo.css') or if the chain of files referencing other files is too deep to resolve in several passes. In the latter case, increase the number of passes usingManifestStaticFilesStorage.max_post_process_passes.- When using
ManifestStaticFilesStorage, static files not found in the manifest at runtime now raise aValueErrorinstead of returning an unchanged path. You can revert to the old behavior by settingManifestStaticFilesStorage.manifest_stricttoFalse.
データベースバックエンド API¶
- The
DatabaseOperations.time_trunc_sql()method is added to supportTimeFieldtruncation. It accepts alookup_typeandfield_namearguments and returns the appropriate SQL to truncate the given time fieldfield_nameto a time object with only the given specificity. Thelookup_typeargument can be either'hour','minute', or'second'. - The
DatabaseOperations.datetime_cast_time_sql()method is added to support thetimelookup. It accepts afield_nameandtznamearguments and returns the SQL necessary to cast a datetime value to time value. - To enable
FOR UPDATE SKIP LOCKEDsupport, setDatabaseFeatures.has_select_for_update_skip_locked = True. - The new
DatabaseFeatures.supports_index_column_orderingattribute specifies if a database allows defining ordering for columns in indexes. The default value isTrueand theDatabaseIntrospection.get_constraints()method should include an'orders'key in each of the returned dictionaries with a list of'ASC'and/or'DESC'values corresponding to the the ordering of each column in the index. inspectdbno longer callsDatabaseIntrospection.get_indexes()which is deprecated. Custom database backends should ensure all types of indexes are returned byDatabaseIntrospection.get_constraints().- Renamed the
ignores_quoted_identifier_casefeature toignores_table_name_caseto more accurately reflect how it is used. - The
namekeyword argument is added to theDatabaseWrapper.create_cursor(self, name=None)method to allow usage of server-side cursors on backends that support it.
Dropped support for PostgreSQL 9.2 and PostGIS 2.0¶
Upstream support for PostgreSQL 9.2 ends in September 2017. As a consequence, Django 1.11 sets PostgreSQL 9.3 as the minimum version it officially supports.
Support for PostGIS 2.0 is also removed as PostgreSQL 9.2 is the last version to support it.
Also, the minimum supported version of psycopg2 is increased from 2.4.5 to 2.5.4.
LiveServerTestCase binds to port zero¶
Rather than taking a port range and iterating to find a free port,
LiveServerTestCase binds to port zero and relies on the operating system
to assign a free port. The DJANGO_LIVE_TEST_SERVER_ADDRESS environment
variable is no longer used, and as it’s also no longer used, the
manage.py test --liveserver option is removed.
If you need to bind LiveServerTestCase to a specific port, use the port
attribute added in Django 1.11.2.
django.contrib.auth や i18n ビューでの安全でないリダイレクトに対する保護¶
LoginView、LogoutView (廃止される関数ベースのビュー) および set_language() は、アプリケーションが HTTPS で動作しているとき、非 HTTPS の next URL へのリダイレクトからユーザを保護します。
QuerySet.get_or_create() と update_or_create() の引数の検証¶
警告なしに引数を渡すことでタイポが発生するのを防ぐため、get_or_create() と update_or_create() が、引数がモデルフィールドかどうかをチェックするようになりました。これはプロジェクト内のバグを顕在化するので、後方互換性がないと言えます。
pytz は必須の依存となり、settings.TIME_ZONE = None のサポートは削除されました。¶
Django のタイムゾーン処理をシンプルにするため、pytz が必須の依存となりました。Django とともに自動的にインストールされます。
動作が一般的でなく、また有用性が不確かなので、settings.TIME_ZONE = None は削除されました。システムのタイムゾーンに基づいたタイムゾーンを自動的に検知したい場合、tzlocal を使用できます:
from tzlocal import get_localzone
TIME_ZONE = get_localzone().zone
os.environ['TZ'] もセットすることを除いて、settings.TIME_ZONE = None と同じように動作します。TIME_ZONE をセットするコードを適応できないことを見つけた事例がある場合は、私たちに教えてください <https://groups.google.com/d/topic/django-developers/OAV3FChfuPM/discussion>。
admin テンプレート内の HTML の変更¶
<p class="help"> が <div> タグに置き換えられ、ヘルプテキスト内にリストを含められるようになりました。
読み取り専用のフィールドが <p>...</p> ではなく <div class="readonly">...</div> でラップされるようになり、どんな種類の HTML でもフィールドのコンテンツとして使えるようになりました。
テンプレートベースのウィジェットレンダリングの導入による変更¶
django.forms.widgets 内の、ドキュメント化されていないいくつかのクラスが削除されました:
SubWidgetRendererMixin、ChoiceFieldRenderer、RadioFieldRenderer、CheckboxFieldRendererChoiceInput、RadioChoiceInput、CheckboxChoiceInput
The undocumented Select.render_option() method is removed.
Widget.format_output() メソッドは削除されました。代わりにカスタムウィジェットテンプレートを使用してください。
いくつかのウィジェット値 (例えば <select> オプション) が、settings.USE_L10N=True の場合にローカル化されるようになりました。ローカル化を無効にする localize テンプレートタグを使ったカスタムウィジェットテンプレートを使用すれば、旧来の動作に戻すことができます。
django.template.backends.django.Template.render() prohibits non-dict context¶
For compatibility with multiple template engines,
django.template.backends.django.Template.render() (returned from high-level
template loader APIs such as loader.get_template()) must receive a
dictionary of context rather than Context or RequestContext. If you
were passing either of the two classes, pass a dictionary instead – doing so
is backwards-compatible with older versions of Django.
マイグレーション処理でのモデル状態の変更¶
マイグレーション適用のスピードを改善するため、処理が必要とするまで関連モデルのレンダリングを送らせるようになりました (例: RunPython)。database_forwards() や database_backwards() の from_state 引数からモデルクラスやモデルインスタンスを操作するような独自の処理を作成していた場合、独自のマイグレーション処理を記述する で説明しているように、clear_delayed_apps_cache() メソッドを使ってモデル状態をレンダリングする必要があります。
その他¶
フィードのアイテムが
pubdateやupdateddate属性を持たない場合、SyndicationFeed.latest_post_date()がタイムゾーン情報を持たない日時ではなく現在の UTC 日/時を返すようになりました。CSRF の失敗が
django.requestではなくdjango.security.csrfロガーに記録されるようになりました。ALLOWED_HOSTSバリデーションが、テスト時に無効化されないようになりました。アプリケーションが独自のホスト名でのテストを含む場合、そのホスト名をALLOWED_HOSTSに含める必要があります。Tests and multiple host names を参照してください。ModelAdmin.list_displayで外部キーの ID (e.g.'field_id') を使用すると関連オブジェクトの ID を表示するようになりました。旧来の動作であるオブジェクトの文字列表現を使いたい場合は、_idサフィックスを削除してください。モデルフォーム内で、
null=TrueのCharFieldが、ブランク値に対して空の文字列ではなく``NULL`` を保存するようになりました。Oracleでは、データベースが値を
NULLとして解釈するため、Model.validate_unique()が一意性に対する空の文字列をチェックしなくなりました。AbstractUserをサブクラス化してclean()をオーバーライドする場合、super()を呼ぶようにしてください。モデルフォームバリデーションのような場合に標準化が適用されるよう、新たなAbstractUser.clean()メソッド内でBaseUserManager.normalize_email()が呼ばれます。EmailFieldとURLFieldが裸のキーワード引数を受け付けなくなりました。これらのフィールドは常に空白を取り除き、古いバージョンの Django では効果がないので削除してください。フォームウィジェットでレンダリングされる
checkedとselected属性が、XHTML のchecked='checked'やselected='selected'ではなく HTML5 ブール値シンタックスを使用するようになりました。RelatedManager.add()、remove()、clear()、set()がprefetch_related()キャッシュをクリアするようになりました。保存した値を失わないように、
teardown_test_environment()を呼び出す前に 2 度めの呼び出しをした場合、setup_test_environment()がエラーを投げるようになりました。DjangoJSONEncoder(Django 1.0 でリネームされました) に対する、ドキュメント化していないDateTimeAwareJSONEncoderエイリアスが削除されました。DEBUGがFalseかつOPTIONS['loaders']を指定していないとき、cached template loaderが有効化されるようになりました。スレッドセーフではないテンプレートタグ がある場合、後方互換性がない可能性があります。古いコンテンツタイプ削除のプロンプトが、
migrateコマンド後に表示されなくなりました。代わりに、新たなremove_stale_contenttypesコマンドを使用してください。IntegerFieldに対する admin のウィジェットがtype="text"ではなくtype="number"を使うようになりました。条件付き HTTP ヘッダが、古い RFC 2616 ではなく RFC 7232 条件付きリクエストの仕様によって解析および比較されるようになりました。
patch_response_headers()がLast-Modifiedヘッダを追加しないようになりました。RFC 7234#section-4.2.2 によると、明示的な有効期限を提供する他のキャッシングヘッダ (例えばExpiresやCache-Control) とともに無用となりました。UpdateCacheMiddlewareおよびadd_never_cache_headers()はpatch_response_headers()を呼び出すため、この変更の影響を受けます。admin テンプレート内で、
<p class="help">が<div>タグに置き換えられ、ヘルプテキスト内にリストを含められるようになりました。ConditionalGetMiddlewareがDateヘッダをセットしなくなりました。ウェブサーバがこのヘッダをセットするからです。また、Content-Lengthヘッダもセットしなくなりました。これは、CommonMiddlewareがこのヘッダをセットするようになったからです。If you have a middleware that modifies a response’s content and appears before
CommonMiddlewarein theMIDDLEWAREorMIDDLEWARE_CLASSESsettings, you must reorder your middleware so that responses aren’t modified afterContent-Lengthis set, or have the response modifying middleware reset theContent-Lengthheader.すべてのアプリケーションのモデルが読み込まれる前に呼び出された場合、
get_model()およびget_models()がAppRegistryNotReadyを投げるようになりました。以前は対象のアプリケーションのモデルが読み込まれることのみが必須で、リレーションシップのセットアップなしでモデルを返すことができました。get_model()の旧来の動作が必要な場合は、require_ready引数をFalseにセットしてください。無用な
BaseCommand.can_import_settings属性が削除されました。ドキュメント化されていなかった
django.utils.functional.lazy_propertyが削除されました。非マルチパートのリクエストとの整合性のため、
MultiPartParser.parse()がrequest.POSTを不変のままにするようになりました。したがってこのQueryDictを修正する場合は、まずコピーする必要があります (例:request.POST.copy())。cx_Oracle5.2 未満へのサポートが削除されました。IPython 1.0 未満へのサポートが
shellコマンドから削除されました。The signature of private API
Widget.build_attrs()changed fromextra_attrs=None, **kwargstobase_attrs, extra_attrs=None.File-like objects (e.g.,
StringIOandBytesIO) uploaded to anImageFieldusing the test client now require anameattribute with a value that passes thevalidate_image_file_extensionvalidator. See the note inClient.post().
1.11 で非推奨となった機能¶
models.permalink() デコレータ¶
代わりに django.urls.reverse() を使用してください。例えば:
from django.db import models
class MyModel(models.Model):
...
@models.permalink
def url(self):
return ('guitarist_detail', [self.slug])
は、以下のようになります:
from django.db import models
from django.urls import reverse
class MyModel(models.Model):
...
def url(self):
return reverse('guitarist_detail', args=[self.slug])
その他¶
- 新たなクラスベースビュー
LoginViewとLogoutViewが採用されたため、contrib.authのlogin()およびlogout()関数ベースビューは非推奨となりました。 contrib.auth.views.logout_then_login()の無用のextra_contextパラメータが非推奨となりました。- 新たなクラスベースビュー
PasswordChangeView、PasswordChangeDoneView、PasswordResetView、PasswordResetDoneView、PasswordResetConfirmView、PasswordResetCompleteViewが採用されたため、contrib.authのpassword_change()、password_change_done()、password_reset()、password_reset_done()、password_reset_confirm()、password_reset_complete()は非推奨となりました。 django.test.runner.setup_databases()がdjango.test.utils.setup_databases()に移動しました。旧来の場所は非推奨となります。django.utils.text.format_lazy()が採用されたため、django.utils.translation.string_concat()は非推奨となりました。string_concat(*strings)はformat_lazy('{}' * len(strings), *strings)で置き換えることができます。PyLibMCCacheキャッシュバックエンドに対して、pylibmc動作設定をOPTIONSのトップレベル属性として渡すことは非推奨となりました。代わりに、OPTIONS内のbehaviorsキー下にセットしてください。- 新たな
allowed_hostsが採用されたため、django.utils.http.is_safe_url()のhostは非推奨となりました。 - 有用性よりも混乱の原因になることが多いため、
{% include %}テンプレートタグをレンダリングするときに投げられる例外を無効化することは非推奨となりました。Django 2.1 で、この例外は投げられるようになります。 DatabaseIntrospection.get_constraints()が採用されたため、DatabaseIntrospection.get_indexes()は非推奨となりました。authenticate()が認証バックエンドのauthenticate()メソッドにrequest引数を渡すようになりました。requestを第 1 省略可能引数として受け取らないメソッドへのサポートは Django 2.1 で削除されます。- 設定にかかわらず
ETagヘッダをレスポンスに追加するようになったConditionalGetMiddlewareが採用されたため、USE_ETAGS設定は非推奨となりました。CommonMiddlewareおよびdjango.utils.cache.patch_response_headers()は非推奨が終了するときに ETags をセットしなくなります。 Model._meta.auto_field が None かどうかをチェックする方法が採用されたので、Model._meta.has_auto_fieldは非推奨となりました。url()内でiLmsu#で正規表現グループを使用することは非推奨となりました。大文字と小文字を区別しない URL に対して有用なグループは(?i)のみとなりますが、大文字と小文字を区別しない URL は、例えば検索エンジン用に複数のエントリを作成するため、適切ではありません。 代わりの解決方法として、URL 内で大文字を検索して小文字の同等の URL にリダイレクトするようなhandler404を作成する方法があります。Widget.render()メソッドにrenderer引数が追加されました。廃止されるまでは、この引数を受け取らないメソッドも動作します。