August 1, 2016
Welcome to 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.
See the Upgrading Django to a newer version guide if you’re updating an existing project.
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.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.
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.
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
¶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 /
.Content-Security-Policy
HTTP header if you wish.InlineModelAdmin.classes
attribute allows specifying
classes on inline fieldsets. Inlines with a collapse
class will be
initially collapsed and their header will have a small “show” link.object-tools
block on a
model’s changelist will now be rendered (without the add button). This makes
it easier to add custom tools in this case.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.ModelAdmin.raw_id_fields
now have a link
to object’s change form.DateFieldListFilter
if the
field is nullable.django.contrib.auth
¶django.contrib.auth.hashers.PBKDF2PasswordHasher
to change the
default value.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.backend
argument to django.contrib.auth.login()
to allow using it without credentials.LOGOUT_REDIRECT_URL
setting controls the redirect of the
django.contrib.auth.views.logout()
view, if the view doesn’t get a
next_page
argument.redirect_authenticated_user
parameter for the
django.contrib.auth.views.login()
view allows redirecting
authenticated users visiting the login page.AllowAllUsersModelBackend
and
AllowAllUsersRemoteUserBackend
ignore
the value of User.is_active
, while
ModelBackend
and
RemoteUserBackend
now reject inactive
users.django.contrib.gis
¶GEOSGeometry.unary_union
property computes the
union of all the elements of this geometry.GEOSGeometry.covers()
binary predicate.GDALBand.statistics()
method and
mean
and std
attributes.MakeLine
aggregate and GeoHash
function on SpatiaLite.Difference
,
Intersection
, and
SymDifference
functions on MySQL.trim
and
precision
properties
of WKTWriter
allow controlling
output of the fractional part of the coordinates in WKT.LineString.closed
and
MultiLineString.closed
properties.properties
dictionary if specific fields
aren’t specified.GDALBand.data()
method was added. Band data can
now be updated with repeated values efficiently.IsValid
and
MakeValid
, as well as the
isvalid
lookup, all for PostGIS. This allows filtering and
repairing invalid geometries on the database side.django.contrib.postgres
¶HStoreField
now
casts its keys and values to strings.django.contrib.sessions
¶clearsessions
management command now removes file-based
sessions.django.contrib.sites
¶Site
model now supports
natural keys.django.contrib.staticfiles
¶static
template tag now uses django.contrib.staticfiles
if it’s in INSTALLED_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 the staticfiles
app is installed.collectstatic --ignore
option with a custom AppConfig
.CSRF_FAILURE_VIEW
, views.csrf.csrf_failure()
now
accepts an optional template_name
parameter, defaulting to
'403_csrf.html'
, to control the template used to render the page.DatabaseFeatures.can_return_ids_from_bulk_insert=True
and implement
DatabaseOperations.fetch_returned_insert_ids()
to set primary keys
on objects created using QuerySet.bulk_create()
.as_sql()
methods of various expressions
(Func
, When
, Case
, and OrderBy
) to allow database backends to
customize them without mutating self
, which isn’t safe when using
different database backends. See the arg_joiner
and **extra_context
parameters of Func.as_sql()
for an
example.get_accessed_time()
,
get_created_time()
, and
get_modified_time()
. They return a
timezone-aware datetime
if USE_TZ
is True
and a naive
datetime
in the local timezone otherwise.Storage.generate_filename()
method makes it easier
to implement custom storages that don’t use the os.path
calls previously
in FileField
.Media
is now served using
django.contrib.staticfiles
if installed.<input>
tag rendered by CharField
now includes
a minlength
attribute if the field has a min_length
.required
HTML attribute. Set the new
Form.use_required_attribute
attribute to False
to disable it. The required
attribute isn’t
included on forms of formsets because the browser validation may not be
correct when adding and deleting formsets.i18n_patterns()
helper function can now be
used in a root URLConf specified using request.urlconf
.prefix_default_language
parameter for
i18n_patterns()
to False
, 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 next
parameter in POST
or
GET
.JavaScriptCatalog
and
JSONCatalog
class-based views supersede the
deprecated javascript_catalog()
and json_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 the djangojs
translation 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.check --fail-level
option allows specifying the message
level that will cause the command to exit with a non-zero status.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.shell --interface
option now accepts python
to force use of
the “plain” Python interpreter.shell --command
option lets you run a command as Django and
exit, instead of opening the interactive shell.dumpdata
if a proxy model is specified (which
results in no output) without its concrete parent.BaseCommand.requires_migrations_checks
attribute
may be set to True
if 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.call_command()
now
accepts a command object as the first argument.shell
command supports tab completion on systems using
libedit
, e.g. macOS.inspectdb
command lets you choose what tables should be
inspected by specifying their names as arguments.enum.Enum
objects.elidable
argument to the
RunSQL
and
RunPython
operations to allow them
to be removed when squashing migrations.atomic
attribute on a Migration
.migrate
and makemigrations
commands now check for a
consistent migration history. If they find
some unapplied dependencies of an applied migration,
InconsistentMigrationHistory
is raised.pre_migrate()
and
post_migrate()
signals now dispatch their
migration plan
and apps
.ForeignKey
pointing to a proxy model is now
accessible as a descriptor on the proxied model class and may be referenced in
queryset filtering.Field.rel_db_type()
method returns the database column data type for fields such as ForeignKey
and OneToOneField
that point to another field.arity
class attribute is added to
Func
. This attribute can be used to set the number
of arguments the function accepts.BigAutoField
which acts much like an
AutoField
except that it is guaranteed
to fit numbers from 1
to 9223372036854775807
.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.prefetch_related_objects()
function is now a
public API.QuerySet.bulk_create()
sets the primary key on objects when using PostgreSQL.Cast
database function.Extract
functions to extract
datetime components as integers, such as year and hour.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.Meta.base_manager_name
and
Meta.default_manager_name
options allow controlling
the _base_manager
and
_default_manager
, respectively.request.user
to the debug view.HttpResponse
methods
readable()
and
seekable()
to make an instance a
stream-like object and allow wrapping it with io.TextIOWrapper
.HttpRequest.content_type
and
content_params
attributes which are
parsed from the CONTENT_TYPE
header.request.COOKIES
is simplified to better match the behavior
of browsers. request.COOKIES
may now contain cookies that are invalid
according to RFC 6265 but are possible to set via document.cookie
.django.core.serializers.json.DjangoJSONEncoder
now knows how to
serialize lazy strings, typically used for translatable content.autoescape
option to the
DjangoTemplates
backend and the
Engine
class.is
and is not
comparison operators to the if
tag.dictsort
to order a list of lists by an element at a
specified index.debug()
context processor
contains queries for all database aliases instead of only the default alias.extends
and
include
template tags.TestCase
now checks deferrable
database constraints at the end of each test.test --tag
and test
--exclude-tag
options.django.contrib.sessions
is not in INSTALLED_APPS
.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_negative
boolean parameter, defaulting to False
, to allow
negative integers.هشدار
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.
AreaField
uses an unspecified underlying numeric type that could in
practice be any numeric Python type. decimal.Decimal
values retrieved
from the database are now converted to float
to make it easier to combine
them with values used by the GIS libraries.supports_temporal_subtraction
database feature flag to True
and
implement the DatabaseOperations.subtract_temporals()
method. This
method should return the SQL and parameters required to compute the
difference in microseconds between the lhs
and rhs
arguments in the
datatype used to store DurationField
._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)
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:
'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.
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()
.
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
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
¶add_postgis_srs()
backwards compatibility alias for
django.contrib.gis.utils.add_srs_entry()
is removed.Area
aggregate function now returns a float
instead of decimal.Decimal
.
(It’s still wrapped in a measure of square meters.)GEOSGeometry
representation (WKT
output) is trimmed by default. That is, instead of
POINT (23.0000000000000000 5.5000000000000000)
, you’ll get
POINT (23 5.5)
.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 towards 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.
repr()
of a QuerySet
is wrapped in <QuerySet >
to
disambiguate it from a plain list when debugging.utils.version.get_version()
returns PEP 440 compliant release
candidate versions (e.g. ‘1.10rc1’ instead of ‘1.10c1’).LOGOUT_URL
setting 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/'
.close()
method such as files and generators passed to
HttpResponse
are now closed immediately instead of when
the WSGI server calls close()
on the response.transaction.atomic()
call in QuerySet.update_or_create()
is removed. This may affect query counts tested by
TransactionTestCase.assertNumQueries()
.skip_validation
in BaseCommand.execute(**options)
is
removed. Use skip_checks
(added in Django 1.7) instead.loaddata
now raises a CommandError
instead of showing a
warning when the specified fixture file is not found.LogEntry.change_message
attribute, it’s
now better to call the LogEntry.get_change_message()
method which will
provide the message in the current language.TemplateDoesNotExist
if a nonexistent
template_name
is specified.choices
keyword argument of the Select
and
SelectMultiple
widgets’ render()
method is removed. The choices
argument of the render_options()
method is also removed, making
selected_choices
the first argument.options
, e.g.
options['verbosity']
, instead of options.get()
and no longer perform
any type coercion. This could be a problem if you’re calling commands using
Command.execute()
(which bypasses the argument parser that sets a default
value) instead of call_command()
. Instead of
calling Command.execute()
, pass the command object as the first argument
to call_command()
.ModelBackend
and
RemoteUserBackend
now reject inactive
users. This means that inactive users can’t login and will be logged
out if they are switched from is_active=True
to False
. If you need
the previous behavior, use the new
AllowAllUsersModelBackend
or
AllowAllUsersRemoteUserBackend
in AUTHENTICATION_BACKENDS
instead.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.base_field
attribute of
RangeField
is now a type of field,
not an instance of a field. If you have created a custom subclass of
RangeField
, you should change the
base_field
attribute.is_authenticated()
or is_anonymous()
in a custom user
model, you must convert them to attributes or properties as described in
the deprecation note.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 new
ModelAdmin.save_as_continue
attribute to False
.required
HTML attribute. Set the
Form.use_required_attribute
attribute to False
to disable it. You could also add the novalidate
attribute to <form>
if you don’t want browser validation. To disable
the required
attribute on custom widgets, override the
Widget.use_required_attribute()
method.HEAD
requests or responses with a status_code
of 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 receives django.db.models.DEFERRED
as the value
of deferred fields.Model._deferred
attribute is removed as dynamic model classes when
using QuerySet.defer()
and only()
is removed.Storage.save()
no longer
replaces '\'
with '/'
. This behavior is moved to
FileSystemStorage
since 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’s save()
method.FileField
methods get_directory_name()
and get_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, override FileField.generate_filename()
or
Storage.generate_filename()
instead. It
might be possible to use upload_to
also.AdminEmailHandler
is no longer truncated at
989 characters. If you were counting on a limited length, truncate the subject
yourself.django.db.models.expressions.Date
and DateTime
are removed. The new Trunc
expressions
provide the same functionality._base_manager
and _default_manager
attributes are removed from
model instances. They remain accessible on the model class.del obj.field
,
reloads the field’s value instead of raising AttributeError
.AbstractBaseUser
and override clean()
, be sure it
calls super()
. AbstractBaseUser.normalize_username()
is called in
a new AbstractBaseUser.clean()
method.django.forms.models.model_to_dict()
returns a queryset rather
than a list of primary keys for ManyToManyField
s.django.contrib.staticfiles
is
installed, the static
template tag uses the staticfiles
storage
to construct the URL rather than simply joining the value with
STATIC_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
.USE_L10N
is True
, localization is now applied for the
date
and time
filters when no format string is
specified. The DATE_FORMAT
and TIME_FORMAT
specifiers from the active
locale are used instead of the settings of the same name.Instead of assigning related objects using direct assignment:
>>> new_list = [obj1, obj2, obj3]
>>> e.related_set = new_list
Use the set()
method
added in Django 1.9:
>>> e.related_set.set([obj1, obj2, obj3])
This prevents confusion about an assignment resulting in an implicit save.
Storage
API¶The old, non-timezone-aware methods accessed_time()
, created_time()
,
and modified_time()
are deprecated in favor of the new get_*_time()
methods.
Third-party storage backends should implement the new methods and mark the old
ones as deprecated. Until then, the new get_*_time()
methods on the base
Storage
class convert datetime
s from
the old methods as required and emit a deprecation warning as they do so.
Third-party storage backends may retain the old methods as long as they wish to support earlier versions of Django.
django.contrib.gis
¶get_srid()
and set_srid()
methods of
GEOSGeometry
are deprecated in favor
of the srid
property.get_x()
, set_x()
, get_y()
, set_y()
, get_z()
, and
set_z()
methods of Point
are deprecated
in favor of the x
, y
, and z
properties.get_coords()
and set_coords()
methods of
Point
are deprecated in favor of the
tuple
property.cascaded_union
property of
MultiPolygon
is deprecated in favor of the
unary_union
property.django.contrib.gis.utils.precision_wkt()
function is deprecated in
favor of WKTWriter
.CommaSeparatedIntegerField
model field¶CommaSeparatedIntegerField
is deprecated in favor of
CharField
with the
validate_comma_separated_integer_list()
validator:
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])
If you’re using Oracle, CharField
uses a different database field type
(NVARCHAR2
) than CommaSeparatedIntegerField
(VARCHAR2
). Depending
on your database settings, this might imply a different encoding, and thus a
different length (in bytes) for the same contents. If your stored values are
longer than the 4000 byte limit of NVARCHAR2
, you should use TextField
(NCLOB
) instead. In this case, if you have any queries that group by the
field (e.g. annotating the model with an aggregation or using distinct()
)
you’ll need to change them (to defer the field).
__search
query lookup¶The search
lookup, which supports MySQL only and is extremely limited in
features, is deprecated. Replace it with a custom 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()
and User.is_anonymous()
as methods¶The is_authenticated()
and is_anonymous()
methods of
AbstractBaseUser
and
AnonymousUser
classes are now
properties. They will still work as methods until Django 2.0, but all usage
in Django now uses attribute access.
For example, if you use
AuthenticationMiddleware
and want
to know whether the user is currently logged-in you would use:
if request.user.is_authenticated:
... # Do something for logged-in users.
else:
... # Do something for anonymous users.
instead of request.user.is_authenticated()
.
This change avoids accidental information leakage if you forget to call the method, e.g.:
if request.user.is_authenticated:
return sensitive_information
If you override these methods in a custom user model, you must change them to properties or attributes.
Django uses a CallableBool
object to allow these attributes to work as both
a property and a method. Thus, until the deprecation period ends, you cannot
compare these properties using the is
operator. That is, the following
won’t work:
if request.user.is_authenticated is True:
...
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.
makemigrations --exit
option is deprecated in favor of the
makemigrations --check
option.django.utils.functional.allow_lazy()
is deprecated in favor of the new
keep_lazy()
function which can be used with a
more natural decorator syntax.shell --plain
option is deprecated in favor of -i python
or
--interface python
.django.core.urlresolvers
module is deprecated in
favor of its new location, django.urls
.Context.has_key()
method is deprecated in favor of in
.virtual_fields
of Model._meta
is
deprecated in favor of private_fields
.virtual_only
in
Field.contribute_to_class()
and virtual
in
Model._meta.add_field()
are deprecated in favor of private_only
and private
, respectively.javascript_catalog()
and json_catalog()
views are deprecated in
favor of class-based views JavaScriptCatalog
and JSONCatalog
.OneToOneField
to a
parent_link
is deprecated. Add parent_link=True
to such fields.Widget._format_value()
is made public and renamed to
format_value()
. The old name will work
through a deprecation period.FileField
methods get_directory_name()
and get_filename()
are deprecated in favor of performing this work in
Storage.generate_filename()
).settings.MIDDLEWARE_CLASSES
are
deprecated. Adapt old, custom middleware and
use the new MIDDLEWARE
setting.These features have reached the end of their deprecation cycle and are removed in Django 1.10. See Features deprecated in 1.8 for details, including how to remove usage of these features.
SQLCompiler
directly as an alias for calling its
quote_name_unless_alias
method is removed.cycle
and firstof
template tags are removed from the future
template tag library.django.conf.urls.patterns()
is removed.prefix
argument to
django.conf.urls.i18n.i18n_patterns()
is removed.SimpleTestCase.urls
is removed.for
template tag
raises an exception rather than failing silently.reverse()
URLs using a dotted Python path
is removed.LOGIN_URL
and
LOGIN_REDIRECT_URL
settings is removed.optparse
is dropped for custom management commands.django.core.management.NoArgsCommand
is removed.django.core.context_processors
module is removed.django.db.models.sql.aggregates
module is removed.django.contrib.gis.db.models.sql.aggregates
module is removed.django.db.sql.query.Query
are
removed:aggregates
and aggregate_select
add_aggregate
, set_aggregate_mask
, and
append_aggregate_mask
.django.template.resolve_variable
is removed.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()
error_message
argument of django.forms.RegexField
is removed.unordered_list
filter no longer supports old style lists.view
arguments to url()
is removed.django.forms.Form._has_changed()
to has_changed()
is removed.removetags
template filter is removed.remove_tags()
and strip_entities()
functions in
django.utils.html
is removed.is_admin_site
argument to
django.contrib.auth.views.password_reset()
is removed.django.db.models.field.subclassing.SubfieldBase
is removed.django.utils.checksums
is removed.original_content_type_id
attribute on
django.contrib.admin.helpers.InlineAdminForm
is removed.FormMixin.get_form()
to be
defined with no default value for its form_class
argument is removed.TEMPLATES
setting:ALLOWED_INCLUDE_ROOTS
TEMPLATE_CONTEXT_PROCESSORS
TEMPLATE_DEBUG
TEMPLATE_DIRS
TEMPLATE_LOADERS
TEMPLATE_STRING_IF_INVALID
django.template.loader.BaseLoader
is
removed.get_template()
and
select_template()
no longer accept a
Context
in their
render()
method.dict
and backend-dependent template objects instead of
Context
and Template
respectively.current_app
parameter for the following function and classes is
removed:django.shortcuts.render()
django.template.Context()
django.template.RequestContext()
django.template.response.TemplateResponse()
dictionary
and context_instance
parameters for the following
functions are removed:django.shortcuts.render()
django.shortcuts.render_to_response()
django.template.loader.render_to_string()
dirs
parameter for the following functions is removed:django.template.loader.get_template()
django.template.loader.select_template()
django.shortcuts.render()
django.shortcuts.render_to_response()
'django.contrib.auth.middleware.SessionAuthenticationMiddleware'
is in
MIDDLEWARE_CLASSES
. SessionAuthenticationMiddleware
no longer has
any purpose and can be removed from MIDDLEWARE_CLASSES
. It’s kept as
a stub until Django 2.0 as a courtesy for users who don’t read this note.django.db.models.Field.related
is removed.--list
option of the migrate
management command is removed.ssi
template tag is removed.=
comparison operator in the if
template tag is
removed.Storage.get_available_name()
and Storage.save()
to be defined without a max_length
argument are
removed.%(<foo>)s
syntax in ModelFormMixin.success_url
is removed.GeoQuerySet
aggregate methods collect()
, extent()
, extent3d()
,
make_line()
, and unionagg()
are removed.ContentType.name
when creating a content type
instance is removed.allow_migrate
is removed.{% cycle %}
that uses comma-separated arguments
is removed.Signer
issued when given an
invalid separator is now a ValueError
.Jul 27, 2022