2 Desember 2017
Selamat datang di Django 2.0!
Catatan terbitan ini melingkupi new features, sama halnya beberapa backwards incompatible changes anda ingin sadari dari ketika meningkatkan dari Django 1.11 atau versi terlama. Kami telah dropped some features yang telah mencapai akhir dari siklus pengusangan mereka, dan kami telah begun the deprecation process for some features.
Terbitan ini memulai Django menggunakan a loose form of semantic versioning, tetapi tidak ada perubahan utama ketidaksesuaian kebelakang yang mungkin diharapkan dari terbitan 2.0. Peningkatan harus berupa jumlah usaha sama seperti terbitan-terbitan fitur lampau.
Lihat panduan Meningkatkan Django ke versi terbaru jika anda sedang memperbaharui proyek yang ada.
Django 2.0 supports Python 3.4, 3.5, 3.6, and 3.7. We highly recommend and only officially support the latest release of each series.
Urutan DJango 1.11.x adalah terakhir untuk mendukung Python 2.7.
Django 2.0 akan menjadi urutan terbitan terakhir untuk mendukung Python 3.4. Jika anda berencana sebuah pengembangan daru Python 3.4 diluar akhir-hidup untuk Django 2.0 (April 2019), tetap dengan Django 1.11 LTS (didukung sampai April 2020) sebagai gantinya. Catat, bagaimanapun, bahwa akhir-hidup untuk Python 3.4 adalah Maret 2019.
Mengikuti terbitan dari Django 2.0, kami anjurkan bahwa penulis aplikasi pihak-ketiga menjatuhkan dukungan untuk semua versi Django sebelum 1.11. Pada saat itu, anda harus dapat menjalankan percobaan paket anda menggunakan python -Wd sehingga peringatan pengusangan akan muncul. Setelah membuat perbaikan peringatan pengusangan apliaksi anda harus sesuai dengan Django 2.0.
Fungsi baru django.urls.path() mengizinkan lebih mudah, sintaksis perutean URL lebih dibaca. Sebagai contoh, contoh ini dari terbitan Django sebelumnya:
url(r'^articles/(?P<year>[0-9]{4})/$', views.year_archive),
dapat ditulis sebagai:
path('articles/<int:year>/', views.year_archive),
Sintaksis baru mendukung jenis paksaan parameter URL. Dalam contoh, tampilan akan menerima argumen katakunci year sebagai sebuah integer daripada sebuah string. Juga, URL yang akan cocok sedikit kurang dibatasi dalam penulisan kembali contoh. Sebagai contoh, tahun 10000 akan sekarang cocok karena tahun integer tidak dibatasi untuk menjadi tepat panjang empat angka ketika mereka berada di regular expression.
Fungsi django.conf.urls.url() dari versi sebelumnya sekarang tersedia sebagai django.urls.re_path(). Tempat lama tetap untuk kesesuaian kebelakang, tanpa sebuah pengusangan dekat. Fungsi lama django.conf.urls.include() sekarang dapat diimpor dari django.urls sehingga anda dapat menggunakan from django.urls import include, path, re_path dalam URLconf and.
Dokumen Pengirim URL ditulis kembali untuk ditampilkan sintaksis baru dan menyediakan lebih rinci.
contrib.admin ramah seluler¶Admin sekarang bergantian dan mendukung semua perangkat seluler utama. Peramban lama mungkin mengalami tingkaran beragam dari pengurangan yang anggun.
Pernyataan baru Window mengizinkan menambahkan sebuah klausa OVER pada queryset. Anda dapat menggunakan :ref:`window functions ` dan :ref:`aggregate functions ` dalam pernyataan.
django.contrib.admin¶ModelAdmin.autocomplete_fields attribute and
ModelAdmin.get_autocomplete_fields() method allow using a
Select2 search widget for ForeignKey and
ManyToManyField.django.contrib.auth¶django.contrib.gis¶AsGeoJSON, fungsi GeoHash, fungsi IsValid, pencarian isvalid, dan :ref:`distance lookups `.Azimuth dan LineLocatePoint, didukung PostGIS dan SpatiaLite.GEOSGeometry apapun diimpor dari GeoJSON sekarang mempunyai kumpulan SRIDnya.OSMWidget.default_zoom untuk menyesuaikan tingkatan awalan perbesar peta.metadata, info, dan metadata.GDALRaster menggunakan papsz_options.GDALRaster dalam sistem berkas internal virtual. Raster sekarang dapat :ref:`created from and converted to binary data ` dalam-memori.GDALBand.color_interp() mengembalikan penafsiran warna untuk pita.django.contrib.postgres¶distinct untuk ArrayAgg menentukan jika nilai-nilai penggabungan akan dibedakan.RandomUUID mengembalikan sebuah versi 4 UUID. Itu membutuhkan menggunakan tambahan pgcrypto PostgreSQL yang dapat diaktifkan menggunakan tindakan perpindahan baru CryptoExtension.django.contrib.postgres.indexes.GinIndex sekarang mendukung parameter fastupdate dan gin_pending_list_limit.GistIndex mengizinkan pembuatan indeks-indeks GiST dalam basisdata. Tindakan perpindahan baru BtreeGistExtension memasang tambahan btree_gist untuk menambah dukungan untuk kelas-kelas penghubung yang belum dibuat.inspectdb can now introspect JSONField and various
RangeFields (django.contrib.postgres must be in INSTALLED_APPS).django.contrib.sitemaps¶protocol ke pembangun GenericSitemap.cache.set_many() sekarang mengembalikan daftar dari kunci yang gagal dimasukkan. Untuk backend siap-pakai, kegagalan masukan hanya dapat terjadi pada memcache.File.open() dapat digunakan sebagai pengelola konteks, sebagai contoh with file.open() as f:.date_attrs dan time_attrs untuk SplitDateTimeWidget dan SplitHiddenDateTimeWidget mengizinkan menentukan atribut-atribut HTML berbeda untuk subwidget `DateInput` dan TimeInput (atau tersembunyi).Form.errors.get_json_data() mengembalikan bentuk kesalahan sebagai dictionary sesuai untuk termasuk dalam tanggapan JSON.ContextMixin.extra_context mengizinkan menambahkan konteks dalam View.as_view().inspectdb sekarang menterjemahkan kolom integer tidak bertanda MySQL menjadi PositiveIntegerField atau PositiveSmallIntegerField.makemessages --add-location mengendalikan bentuk komentar dalam berkas-berkas PO.loaddata sekarang dapat read from stdin.diffsettings --output mengizinkan membentuk keluaran dalam sebuah bentuk berbeda yang bersatu.inspectdb sekarang dapat menginterospeksi AutoField jika kolom dibuat sebagai sebuah kolom identitas.dbshell sekarang mendukung sertifikat TLS sisi-klien.squashmigrations --squashed-name mengizinkan menamakan perpindahan yang dihentikan.StrIndex menemukan permulaan indeks dari string didalam string lain.AutoField dan BigAutoField sekarang dibuat sebagai identity columns.chunk_size dari QuerySet.iterator() mengendalikan sejumlah baris diambil oleh klien basisdata Python ketika mengalirkan hasil dari basisdata. Untuk basisdata yang tidak mengukung kursos sisi-peladen, itu mengendalikan sejumlah hasil Django diambil dari penyadur basisdata.QuerySet.earliest(), QuerySet.latest(), dan Meta.get_latest_by sekarang mengizinkan pengurutan berdasarkan beberapa bidang.ExtractQuarter untuk mengambil perempat dari DateField dan DateTimeField, dan menampilkan itu melalui pencarian quarter.TruncQuarter untuk memotong DateField dan DateTimeField untuk hari pertama dari perempat.db_tablespace pada pengindeksan berdasarkan-kelas.Extract sekarang bekerja dengan DurationField.off pada QuerySet.select_for_update(), didukung pada PostgreSQL dan Oracle, untuk mengunci hanya baris dari tabel-tabel tertentu daripada semua tabel terpilih. Itu mungkin berguna khususnya ketika select_for_update() digunakan di hubungan dengan select_related().field_name dari QuerySet.in_bulk() mengizinkan mengambil hasil berdasarkan pada bidang model unik.CursorWrapper.callproc() sekarang mengambil sebuah pilihan dari parameter katakunci, jika backend mendukung fitur ini. Dari backend siap-pakai Django, hanya Oracle mendukung itu.connection.execute_wrapper() mengizinkan :doc:`installing wrappers around execution of database queries `.filter untuk kumpulan siap-pakai mengizinkan :ref:`adding different conditionals ` untuk banyak kumpulan terhadap bidang atau hubungan sama.Meta.ordering.named dari QuerySet.values_list() mengizinkan mengambil hasil sebagai tuple-tuple bernama.FilteredRelation mengizinkan menambahkan sebuah klausa ON pada queryset.Paginator.get_page() untuk menyediakan pola terdokumentasi dari penanganan nomor halaman tidak sah.Engine.get_default() dalam aplikasi pihak-ketiga, itu sekarang mengembalikan mesin pertama jika banyak mesin DjangoTemplates dikonfigurasikan dalam TEMPLATES daripada memunculkan ImproperlyConfigured.LiveServerTestCase.DATAFILE_SIZE, DATAFILE_TMP_SIZE, DATAFILE_EXTSIZE, dan DATAFILE_TMP_EXTSIZE.ProhibitNullCharactersValidator disallows the null
character in the input of the CharField form field
and its subclasses. Null character input was observed from vulnerability
scanning tools. Most databases silently discard null characters, but
psycopg2 2.7+ raises an exception when trying to save a null character to
a char/text field with PostgreSQL.To support native Python 2 strings, older Django versions had to accept both
bytestrings and unicode strings. Now that Python 2 support is dropped,
bytestrings should only be encountered around input/output boundaries (handling
of binary fields or HTTP streams, for example). You might have to update your
code to limit bytestring usage to a minimum, as Django no longer accepts
bytestrings in certain code paths. Python's -b option may help detect
that mistake in your code.
For example, reverse() now uses str() instead of force_text() to
coerce the args and kwargs it receives, prior to their placement in
the URL. For bytestrings, this creates a string with an undesired b prefix
as well as additional quotes (str(b'foo') is "b'foo'"). To adapt, call
decode() on the bytestring before passing it to reverse().
Bagian ini menjelaskan perubahan yang mungkin diperlukan oleh backend basis data pihak ketiga.
DatabaseOperations.datetime_cast_date_sql(), datetime_cast_time_sql(), datetime_trunc_sql(), datetime_extract_sql(), dan date_interval_sql() sekarang hanya mengembalikan SQL untuk melakukan tindakan daripada SQL dan daftar parameter.DatabaseWrapper.display_name dengan nama dari basisdata dimana backend anda bekerja dengannya. Django menggunakan itu dalam beragam pesan, seperti di pemeriksaan sistem.SchemaEditor._alter_column_type_sql() sekarang model daripada table.SchemaEditor._create_index_name() sekarang table_name daripada model.FOR UPDATE OF, setel DatabaseFeatures.has_select_for_update_of = True. jika basisdata membutuhkan bahwa argumen menjadi kolom OF daripada tabel, setel DatabaseFeatures.select_for_update_of_column = True.Window, setel DatabaseFeatures.supports_over_clause menjadi True. Anda mungkin butuh menyesuaikan metode DatabaseOperations.window_start_rows_start_end() dan/atau window_start_range_start_end().DatabaseOperations.cast_char_field_without_max_length dengan jenis data basisdata yang akan digunakan dalam fungsi Cast untuk CharField jika argumen max_length tidak disediakan.DatabaseCreation._clone_test_db() and
get_test_db_clone_settings() is now suffix rather
than number (in case you want to rename the signatures in your backend
for consistency). django.test also now passes those values as strings
rather than as integers.DatabaseIntrospection.get_sequences() method based on the stub in
BaseDatabaseIntrospection.The end of upstream support for Oracle 11.2 is Dec. 2020. Django 1.11 will be supported until April 2020 which almost reaches this date. Django 2.0 officially supports Oracle 12.1+.
MySQL's default isolation level, repeatable read, may cause data loss in
typical Django usage. To prevent that and for consistency with other databases,
the default isolation level is now read committed. You can use the
DATABASES setting to use a different isolation level, if needed.
max_length AbstractUser.last_name ditingkatkan menjadi 150¶A migration for django.contrib.auth.models.User.last_name 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.
Jika anda ingin menyediakan batasan 30 karakter untuk nama terakhir, gunakan formulir penyesuaian:
from django.contrib.auth.forms import UserChangeForm
class MyUserChangeForm(UserChangeForm):
last_name = forms.CharField(max_length=30, required=False)
Jika anda berharap menjaga pembatasan ini dalam admin ketika mengubah pengguna, setel UserAdmin.form untuk menggunakan formulir ini:
from django.contrib.auth.admin import UserAdmin
from django.contrib.auth.models import User
class MyUserAdmin(UserAdmin):
form = MyUserChangeForm
admin.site.unregister(User)
admin.site.register(User, MyUserAdmin)
QuerySet.reverse() dan last() terlarang setelah membelah¶Calling QuerySet.reverse() or last() on a sliced queryset leads to
unexpected results due to the slice being applied after reordering. This is
now prohibited, e.g.:
>>> Model.objects.all()[:2].reverse()
Traceback (most recent call last):
...
TypeError: Cannot reverse a query once a slice has been taken.
To help prevent runtime errors due to incorrect ordering of form field arguments, optional arguments of built-in form fields are no longer accepted as positional arguments. For example:
forms.IntegerField(25, 10)
memunculkan sebuah pengecualian dan harus diganti dengan:
forms.IntegerField(max_value=25, min_value=10)
call_command() mensahkan pilihan dia terima¶call_command() now validates that the argument parser of the command being
called defines all of the options passed to call_command().
For custom management commands that use options not created using
parser.add_argument(), add a stealth_options attribute on the command:
class MyCommand(BaseCommand):
stealth_options = ('option_name', ...)
Sebagai contoh:
models.Index(['headline', '-pub_date'], 'index_name')
memunculkan sebuah pengecualian dan harus diganti dengan:
models.Index(fields=['headline', '-pub_date'], name='index_name')
This will appear as a backwards-incompatible change (IntegrityError:
FOREIGN KEY constraint failed) if attempting to save an existing model
instance that's violating a foreign key constraint.
Foreign keys are now created with DEFERRABLE INITIALLY DEFERRED instead of
DEFERRABLE IMMEDIATE. Thus, tables may need to be rebuilt to recreate
foreign keys with the new definition, particularly if you're using a pattern
like this:
from django.db import transaction
with transaction.atomic():
Book.objects.create(author_id=1)
Author.objects.create(id=1)
Jika anda tidak membuat kembali foreign key sebagai DEFERRED, pertama-tama create() akan gagal sekarang dimana batasan foreign key dipaksakan.
Cadangkan basisdata anda dahulu! Setelah meningkatkan ke Django 2.0, anda dapat kemudian membangun kembali tabel-tabel menggunakan tulisan mirip ini:
from django.apps import apps
from django.db import connection
for app in apps.get_app_configs():
for model in app.get_models(include_auto_created=True):
if model._meta.managed and not (model._meta.proxy or model._meta.swapped):
for base in model.__bases__:
if hasattr(base, '_meta'):
base._meta.local_many_to_many = []
model._meta.local_many_to_many = []
with connection.schema_editor() as editor:
editor._remake_table(model)
This script hasn't received extensive testing and needs adaption for various cases such as multiple databases. Feel free to contribute improvements.
In addition, because of a table alteration limitation of SQLite, it's prohibited
to perform RenameModel and
RenameField operations on models or
fields referenced by other models in a transaction. In order to allow migrations
containing these operations to be applied, you must set the
Migration.atomic attribute to False.
Kelas SessionAuthenticationMiddleware dipindahkan. Itu tidak menyediakan kegunaan sejak autentifikasi sesi tanpa syarat ada di Django 1.10.
The default HTTP error handlers (handler404, etc.) are now callables
instead of dotted Python path strings. Django favors callable references
since they provide better performance and debugging experience.
RedirectView tidak lagi diam NoReverseMatch jika pattern_name tidak ada.
ketika USE_L10N adalah mati, FloatField dan DecimalField sekarang menghormati DECIMAL_SEPARATOR dan THOUSAND_SEPARATOR selama pengesahan. Sebagai contoh, dengan pengaturan:
USE_L10N = False
USE_THOUSAND_SEPARATOR = True
DECIMAL_SEPARATOR = ','
THOUSAND_SEPARATOR = '.'
sebuah masukan dari "1.345" sekarang dirubah ke 1345 daripada 1.345.
Subclasses of AbstractBaseUser are no
longer required to implement get_short_name() and get_full_name().
(The base implementations that raise NotImplementedError are removed.)
django.contrib.admin uses these methods if implemented but doesn't
require them. Third-party apps that use these methods may want to adopt a
similar approach.
Pengaturan bentuk FIRST_DAY_OF_WEEK dan NUMBER_GROUPING sekarang dijaga sebagai integer dalam keluaran tampilan JavaScript dan JSON.
assertNumQueries() now ignores
connection configuration queries. Previously, if a test opened a new database
connection, those queries could be included as part of the
assertNumQueries() count.
The default size of the Oracle test tablespace is increased from 20M to 50M and the default autoextend size is increased from 10M to 25M.
To improve performance when streaming large result sets from the database,
QuerySet.iterator() now fetches 2000 rows at a time instead of 100.
The old behavior can be restored using the chunk_size parameter. For
example:
Book.objects.iterator(chunk_size=100)
Providing unknown package names in the packages argument of the
JavaScriptCatalog view now raises ValueError
instead of passing silently.
A model instance's primary key now appears in the default Model.__str__()
method, e.g. Question object (1).
makemigrations now detects changes to the model field limit_choices_to
option. Add this to your existing migrations or accept an auto-generated
migration for fields that use it.
Performing queries that require automatic spatial transformations now raises NotImplementedError
on MySQL instead of silently using non-transformed geometries.
django.core.exceptions.DjangoRuntimeWarning dipindahkan. Itu hanya digunakan dalam backend cache sebagai sebuah kelas pertengahan dalam warisan CacheKeyWarning dari RuntimeWarning.
Renamed BaseExpression._output_field to output_field. You may need
to update custom expressions.
In older versions, forms and formsets combine their Media with widget
Media by concatenating the two. The combining now tries to preserve
the relative order of elements in each list.
MediaOrderConflictWarning is issued if the order can't be preserved.
django.contrib.gis.gdal.OGRException is removed. It's been an alias for
GDALException since Django 1.8.
Dukungan GEOS 3.3.x dijatuhkan.
The way data is selected for GeometryField is changed to improve
performance, and in raw SQL queries, those fields must now be wrapped in
connection.ops.select. See the Raw queries note in
the GIS tutorial for an example.
context dari Field.from_db_value() dan Expression.convert_value()¶The context argument of Field.from_db_value() and
Expression.convert_value() is unused as it's always an empty dictionary.
The signature of both methods is now:
(self, value, expression, connection)
dari pada:
(self, value, expression, connection, context)
Support for the old signature in custom fields and expressions remains until Django 3.0.
django.db.backends.postgresql_psycopg2 module is deprecated in favor
of django.db.backends.postgresql. It's been an alias since Django 1.9.
This only affects code that imports from the module directly. The
DATABASES setting can still use
'django.db.backends.postgresql_psycopg2', though you can simplify that by
using the 'django.db.backends.postgresql' name added in Django 1.9.django.shortcuts.render_to_response() is deprecated in favor of
django.shortcuts.render(). render() takes the same arguments
except that it also requires a request.DEFAULT_CONTENT_TYPE setting is deprecated. It doesn't interact well
with third-party apps and is obsolete since HTML5 has mostly superseded
XHTML.HttpRequest.xreadlines() is deprecated in favor of iterating over the
request.field_name keyword argument to QuerySet.earliest() and
QuerySet.latest() is deprecated in favor of passing the field
names as arguments. Write .earliest('pub_date') instead of
.earliest(field_name='pub_date').These features have reached the end of their deprecation cycle and are removed in Django 2.0.
See Fitur usang di 1.9 for details on these changes, including how to remove usage of these features.
weak argument to django.dispatch.signals.Signal.disconnect() is
removed.django.db.backends.base.BaseDatabaseOperations.check_aggregate_support()
is removed.django.forms.extras package is removed.assignment_tag helper is removed.host argument to SimpleTestCase.assertsRedirects() is removed.
The compatibility layer which allows absolute URLs to be considered equal to
relative ones when the path is identical is also removed.Field.rel dan Field.remote_field.to dipindahkan.on_delete argument for ForeignKey and OneToOneField is now
required in models and migrations. Consider squashing migrations so that you
have fewer of them to update.django.db.models.fields.add_lazy_relation() dipindahkan.cursor.execute().django.contrib.auth.tests.utils.skipIfCustomUser() dipindahkan.GeoManager dan GeoQuerySet dipindahkan.django.contrib.gis.geoip module is removed.supports_recursion check for template loaders is removed from:django.template.engine.Engine.find_template()django.template.loader_tags.ExtendsNode.find_template()django.template.loaders.base.Loader.supports_recursion()django.template.loaders.cached.Loader.supports_recursion()load_template and load_template_sources template loader methods
are removed.template_dirs argument for template loaders is removed:django.template.loaders.base.Loader.get_template()django.template.loaders.cached.Loader.cache_key()django.template.loaders.cached.Loader.get_template()django.template.loaders.cached.Loader.get_template_sources()django.template.loaders.filesystem.Loader.get_template_sources()django.template.loaders.base.Loader.__call__() dipindahkan.exception parameter
is removed.mime_type attribute of django.utils.feedgenerator.Atom1Feed and
django.utils.feedgenerator.RssFeed is removed.app_name argument to include() is removed.admin.site.urls) as the first
argument to include() is removed.Field._get_val_from_obj() is removed.django.template.loaders.eggs.Loader is removed.current_app parameter to the contrib.auth function-based views is
removed.callable_obj keyword argument to
SimpleTestCase.assertRaisesMessage() is removed.allow_tags attribute on ModelAdmin methods is
removed.enclosure keyword argument to SyndicationFeed.add_item() is
removed.django.template.loader.LoaderOrigin and
django.template.base.StringOrigin aliases for
django.template.base.Origin are removed.See Fitur-fitur diusangkan di 1.10 for details on these changes.
makemigrations --exit option is removed.get_srid() and set_srid() methods of
django.contrib.gis.geos.GEOSGeometry are removed.get_x(), set_x(), get_y(), set_y(), get_z(), and
set_z() methods of django.contrib.gis.geos.Point are removed.get_coords() and set_coords() methods of
django.contrib.gis.geos.Point are removed.cascaded_union property of django.contrib.gis.geos.MultiPolygon
is removed.django.utils.functional.allow_lazy() is removed.shell --plain option is removed.django.core.urlresolvers module is removed in favor of its new
location, django.urls.CommaSeparatedIntegerField is removed, except for support in historical
migrations.Context.has_key() method is removed.django.core.files.storage.Storage.accessed_time(),
created_time(), and modified_time() methods is removed.Meta.default_related_name disetel dipindahkan.__search MySQL dipindahkan._apply_rel_filters() method is removed.User.is_authenticated() and User.is_anonymous() as methods
rather than properties is no longer supported.Model._meta.virtual_fields dipindahkan.virtual_only in Field.contribute_to_class() and
virtual in Model._meta.add_field() are removed.javascript_catalog() dan json_catalog() dipindahkan.django.contrib.gis.utils.precision_wkt() dipindahkan.OneToOneField to a
parent_link is removed.Widget._format_value() dipindahkan.FileField get_directory_name()` dan get_filename() dipindahkan.mark_for_escaping() dan kelas-kelas yang digunakan: EscapeData, EscapeBytes, EscapeText, EscapeString, dan EscapeUnicode dipindahkan.escape sekarang menggunakan django.utils.html.conditional_escape().Manager.use_for_related_fields dipindahkan.Manager inheritance follows MRO inheritance rules. The requirement
to use Meta.manager_inheritance_from_future to opt-in to the behavior is
removed.settings.MIDDLEWARE_CLASSES is
removed.Mar 30, 2019