Django 1.8 has been designated as Django’s second long-term support
release. It will receive security updates for at least three years after its
release. Support for the previous LTS, Django 1.4, will end 6 months from the
release date of Django 1.8.

The Model._meta object has been part of Django since the days of pre-0.96
“Magic Removal” – it just wasn’t an official, stable API. In recognition of
this, we’ve endeavored to maintain backwards-compatibility with the old
API endpoint where possible. However, API endpoints that aren’t part of the
new official API have been deprecated and will eventually be removed. A
guide to migrating from the old API to the new API has been provided.

Django 1.8 defines a stable API for integrating template backends. It includes
built-in support for the Django template language and for
Jinja2. It supports rendering
templates with multiple engines within the same project. Learn more about the
new features in the topic guide and check the
upgrade instructions in older versions of the documentation.

Django now has a UUIDField for storing
universally unique identifiers. It is stored as the native uuid data type
on PostgreSQL and as a fixed length character field on other backends. There
is a corresponding formfield.

Django now has a DurationField for storing periods
of time - modeled in Python by timedelta. It is
stored in the native interval data type on PostgreSQL, as a INTERVALDAY(9)TOSECOND(6) on Oracle, and as a bigint of microseconds on other
backends. Date and time related arithmetic has also been improved on all
backends. There is a corresponding formfield.

Query Expressions allow you to create,
customize, and compose complex SQL expressions. This has enabled annotate
to accept expressions other than aggregates. Aggregates are now able to
reference multiple fields, as well as perform arithmetic, similar to F()
objects. order_by() has also gained the
ability to accept expressions.

TestCase has been refactored to allow for data
initialization at the class level using transactions and savepoints. Database
backends which do not support transactions, like MySQL with the MyISAM storage
engine, will still be able to run these tests but won’t benefit from the
improvements. Tests are now run within two nested
atomic() blocks: one for the whole class and one
for each test.

The class method
TestCase.setUpTestData() adds
the ability to setup test data at the class level. Using this technique can
speed up the tests as compared to using setUp().

Fixture loading within TestCase is now performed once for the whole
TestCase.

The AdminSite.password_change() method now has an extra_context
parameter.

You can now control who may login to the admin site by overriding only
AdminSite.has_permission() and
AdminSite.login_form.
The base.html template has a new block usertools which contains the
user-specific header. A new context variable has_permission, which gets
its value from has_permission(),
indicates whether the user may access the site.

Foreign key dropdowns now have buttons for changing or deleting related
objects using a popup.

The default iteration count for the PBKDF2 password hasher has been
increased by 33%. This backwards compatible change will not affect users who
have subclassed django.contrib.auth.hashers.PBKDF2PasswordHasher to
change the default value.

The MySQL backend no longer strips microseconds from datetime values as
MySQL 5.6.4 and up supports fractional seconds depending on the declaration
of the datetime field (when DATETIME includes fractional precision greater
than 0). New datetime database columns created with Django 1.8 and MySQL 5.6.4
and up will support microseconds. See the MySQL database notes for more details.

The MySQL backend no longer creates explicit indexes for foreign keys when
using the InnoDB storage engine, as MySQL already creates them automatically.

The Oracle backend no longer defines the connection_persists_old_columns
feature as True. Instead, Oracle will now include a cache busting clause
when getting the description of a table.

Storage.get_available_name() and
Storage.save()
now take a max_length argument to implement storage-level maximum
filename length constraints. Filenames exceeding this argument will get
truncated. This prevents a database error when appending a unique suffix to a
long filename that already exists on the storage. See the deprecation
note about adding this argument to your custom
storage classes.

Form widgets now render attributes with a value of True or False
as HTML5 boolean attributes.

The new has_error() method allows checking
if a specific error has happened.

If required_css_class is defined on a form, then
the <label> tags for required fields will have this class present in its
attributes.

The rendering of non-field errors in unordered lists (<ul>) now includes
nonfield in its list of classes to distinguish them from field-specific
errors.

Field now accepts a
label_suffix argument, which will override the
form’s label_suffix. This enables customizing the
suffix on a per-field basis — previously it wasn’t possible to override
a form’s label_suffix while using shortcuts such
as {{form.as_p}} in templates.

After an ImageField has been cleaned and validated, the
UploadedFile object will have an additional image attribute containing
the Pillow Image instance used to check if the file was a valid image. It
will also update UploadedFile.content_type with the image’s content type
as determined by Pillow.

You can now pass a callable that returns an iterable of choices when
instantiating a ChoiceField.

FORMAT_MODULE_PATH can now be a list of strings representing
module paths. This allows importing several format modules from different
reusable apps. It also allows overriding those custom formats in your main
Django project.

inspectdb now outputs Meta.unique_together. It is also able to
introspect AutoField for MySQL and PostgreSQL
databases.

When calling management commands with options using
call_command(), the option name can match the
command line option name (without the initial dashes) or the final option
destination variable name, but in either case, the resulting option received
by the command is now always the dest name specified in the command
option definition (as long as the command uses the argparse module).

The migration operations RunPython
and RunSQL now call the
allow_migrate() method of database routers. The router can use the
newly introduced app_label and hints arguments to make a routing
decision. To take advantage of this feature you need to update the router to
the new allow_migrate signature, see the deprecation section for more details.

Django now logs at most 9000 queries in connections.queries, in order
to prevent excessive memory usage in long-running processes in debug mode.

There is now a model Meta option to define a
defaultrelatedname
for all relational fields of a model.

Pickling models and querysets across different versions of Django isn’t
officially supported (it may work, but there’s no guarantee). An extra
variable that specifies the current Django version is now added to the
pickled state of models and querysets, and Django raises a RuntimeWarning
when these objects are unpickled in a different version than the one in
which they were pickled.

The new Transform.bilateral
attribute allows creating bilateral transformations. These transformations
are applied to both lhs and rhs when used in a lookup expression,
providing opportunities for more sophisticated lookups.

SQL special characters (, %, _) are now escaped properly when a pattern
lookup (e.g. contains, startswith, etc.) is used with an F()
expression as the right-hand side. In those cases, the escaping is performed
by the database, which can lead to somewhat complex queries involving nested
REPLACE function calls.

The query_string argument of QueryDict is now
optional, defaulting to None, so a blank QueryDict can now be
instantiated with QueryDict() instead of QueryDict(None) or
QueryDict('').

The GET and POST attributes of an HttpRequest
object are now QueryDicts rather than dictionaries,
and the FILES attribute is now a MultiValueDict.
This brings this class into line with the documentation and with
WSGIRequest.

In addition to the changes outlined in this section, be sure to review the
deprecation plan for any features that
have 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.

Some operations on related objects such as
add() or direct
assignment ran multiple data modifying queries without wrapping them in
transactions. To reduce the risk of data corruption, all data modifying methods
that affect multiple related objects (i.e. add(), remove(),
clear(), and direct assignment) now perform their data modifying queries
from within a transaction, provided your database supports transactions.

This has one backwards incompatible side effect, signal handlers triggered from
these methods are now executed within the method’s transaction and any
exception in a signal handler will prevent the whole operation.

If you require allowing the assignment of unsaved instances (the old behavior)
and aren’t concerned about the data loss possibility (e.g. you never save the
objects to the database), you can disable this check by using the
ForeignKey.allow_unsaved_instance_assignment attribute. (This attribute was
removed in 1.8.4 as it’s no longer relevant.)

If you have written a custom management command that only accepts positional
arguments and you didn’t specify the args command variable, you might get
an error like Error:unrecognizedarguments:..., as variable parsing is
now based on argparse which doesn’t implicitly accept positional
arguments. You can make your command backwards compatible by simply setting the
args class variable. However, if you don’t have to keep compatibility with
older Django versions, it’s better to implement the new
add_arguments() method as described
in Writing custom django-admin commands.

The method to add custom arguments to the test management command through the
test runner has changed. Previously, you could provide an option_list class
variable on the test runner to add more arguments (à la optparse).
Now to implement the same behavior, you have to create an
add_arguments(cls,parser) class method on the test runner and call
parser.add_argument to add any custom arguments, as parser is now an
argparse.ArgumentParser instance.

A field name that’s longer than the column name length supported by a database
can create problems. For example, with MySQL you’ll get an exception trying to
create the column, and with PostgreSQL the column name is truncated by the
database (you may see a warning in the PostgreSQL logs).

A model check has been introduced to better alert users to this scenario before
the actual creation of database tables.

If you have an existing model where this check seems to be a false positive,
for example on PostgreSQL where the name was already being truncated, simply
use db_column to specify the name that’s being
used.

The check also applies to the columns generated in an implicit
ManyToManyField.through model. If you run into an issue there, use
through to create an explicit model
and then specify db_column on its column(s)
as needed.

Querying for model lookups now checks if the object passed is of correct type
and raises a ValueError if not. Previously, Django didn’t care if the
object was of correct type; it just used the object’s related field attribute
(e.g. id) for the lookup. Now, an error is raised to prevent incorrect
lookups:

The old default 75 character max_length was not capable of storing all
possible RFC3696/5321-compliant email addresses. In order to store all
possible valid email addresses, the max_length has been increased to 254
characters. You will need to generate and apply database migrations for your
affected models (or add max_length=75 if you wish to keep the length on
your current fields). A migration for
django.contrib.auth.models.User.email is included.

The end of upstream support periods was reached in January 2012 for MySQL 5.0
and December 2013 for MySQL 5.1. As a consequence, Django 1.8 sets 5.5 as the
minimum MySQL version it officially supports.

The end of upstream support periods was reached in July 2010 for Oracle 9.2,
January 2012 for Oracle 10.1, and July 2013 for Oracle 10.2. As a consequence,
Django 1.8 sets 11.1 as the minimum Oracle version it officially supports.

Earlier versions of Django granted the CONNECT and RESOURCE roles to the test
user on Oracle. These roles have been deprecated, so Django 1.8 uses the
specific underlying privileges instead. This changes the privileges required
of the main user for running tests (unless the project is configured to avoid
creating a test user). The exact privileges required now are detailed in
Oracle notes.

The AbstractUser.last_login
field now allows null values. Previously, it defaulted to the time when the user
was created which was misleading if the user never logged in. If you are using
the default user (django.contrib.auth.models.User), run the database
migration included in contrib.auth.

If you are using a custom user model that inherits from AbstractUser,
you’ll need to run makemigrations and generate a migration for your
app that contains that model. Also, if wish to set last_login to NULL
for users who haven’t logged in, you can run this query:

The default str representation of
GEOSGeometry objects has been changed from
WKT to EWKT format (including the SRID). As this representation is used in
the serialization framework, that means that dumpdata output will now
contain the SRID value of geometry objects.

Priority of context processors for TemplateResponse brought in line with render¶

The TemplateResponse constructor is designed to be a
drop-in replacement for the render() function. However,
it had a slight incompatibility, in that for TemplateResponse, context data
from the passed in context dictionary could be shadowed by context data returned
from context processors, whereas for render it was the other way
around. This was a bug, and the behavior of render is more appropriate,
since it allows the globally defined context processors to be overridden locally
in the view. If you were relying on the fact context data in a
TemplateResponse could be overridden using a context processor, you will
need to change your code.

The decorators override_settings() and
modify_settings() now act at the class level when used as
class decorators. As a consequence, when overriding setUpClass() or
tearDownClass(), the super implementation should always be called.

Django previously closed database connections between each test within a
TestCase. This is no longer the case as Django now wraps the whole
TestCase within a transaction. If some of your tests relied on the old
behavior, you should have them inherit from TransactionTestCase instead.

In earlier versions of Django, on a model with a reverse foreign key
relationship (for example), model._meta.get_all_related_objects() returned
the relationship as a django.db.models.related.RelatedObject with the
model attribute set to the source of the relationship. Now, this method
returns the relationship as django.db.models.fields.related.ManyToOneRel
(private API RelatedObject has been removed), and the model attribute
is set to the target of the relationship instead of the source. The source
model is accessible on the related_model attribute instead.

AdminSite no longer takes an app_name argument and its app_name
attribute has been removed. The application name is always admin (as
opposed to the instance name which you can still customize using
AdminSite(name="...").

The ModelAdmin.get_object() method (private API) now takes a third
argument named from_field in order to specify which field should match
the provided object_id.

The ModelAdmin.response_delete() method
now takes a second argument named obj_id which is the serialized
identifier used to retrieve the object before deletion.

In order to make built-in template filters that output HTML “safe by default”
when calling them in Python code, the following functions in
django.template.defaultfilters have been changed to automatically escape
their input value:

join

linebreaksbr

linebreaks_filter

linenumbers

unordered_list

urlize

urlizetrunc

You can revert to the old behavior by specifying autoescape=False if you
are passing trusted content. This change doesn’t have any effect when using
the corresponding filters in templates.

Database connections are considered equal only if they’re the same object.
They aren’t hashable any more.

GZipMiddleware used to disable compression
for some content types when the request is from Internet Explorer, in order
to work around a bug in IE6 and earlier. This behavior could affect
performance on IE7 and later. It was removed.

URLField.to_python no longer adds a trailing slash to pathless URLs.

The length template filter now returns 0 for an undefined
variable, rather than an empty string.

ForeignKey.default_error_message['invalid'] has been changed from
'%(model)sinstancewithpk%(pk)rdoesnotexist.' to
'%(model)sinstancewith%(field)s%(value)rdoesnotexist.' If you are
using this message in your own code, please update the list of interpolated
parameters. Internally, Django will continue to provide the
pk parameter in params for backwards compatibility.

UserCreationForm.error_messages['duplicate_username'] is no longer used.
If you wish to customize that error message, override it on the form using the 'unique' key in
Meta.error_messages['username'] or, if you have a custom form field for
'username', using the 'unique' key in its
error_messages argument.

The CacheClass shim has been removed from all cache backends.
These aliases were provided for backwards compatibility with Django 1.3.
If you are still using them, please update your project to use the real
class name found in the BACKEND key of the
CACHES setting.

By default, call_command() now always skips the
check framework (unless you pass it skip_checks=False).

When iterating over lines, File now uses
universal newlines. The following are recognized as ending a line: the
Unix end-of-line convention '\n', the Windows convention '\r\n', and
the old Macintosh convention '\r'.

The Memcached cache backends MemcachedCache and PyLibMCCache will
delete a key if set() fails. This is necessary to ensure the cache_db
session store always fetches the most current session data.

Class-based views that use ModelFormMixin
will raise an ImproperlyConfigured exception
when both the fields and form_class attributes are specified.
Previously, fields was silently ignored.

When following redirects, the test client now raises
RedirectCycleError if it detects a loop or hits a
maximum redirect limit (rather than passing silently).

Translatable strings set as the default parameter of the field are cast
to concrete strings later, so the return type of Field.get_default() is
different in some cases. There is no change to default values which are the
result of a callable.

GenericIPAddressField.empty_strings_allowed is now False. Database
backends that interpret empty strings as null (only Oracle among the backends
that Django includes) will no longer convert null values back to an empty
string. This is consistent with other backends.

When the BaseCommand.leave_locale_alone
attribute is False, translations are now deactivated instead of forcing
the “en-us” locale. In the case your models contained non-English strings and
you counted on English translations to be activated in management commands,
this will not happen any longer. It might be that new database migrations are
generated (once) after migrating to 1.8.

Be careful if you upgrade to Django 1.8 and skip Django 1.7. If you run
manage.pymigrate--fake, this migration will be skipped and you’ll see
a RuntimeError:Errorcreatingnewcontenttypes. exception because the
name column won’t be dropped from the database. Use manage.pymigrate--fake-initial to fake only the initial migration instead.

The new migrate--fake-initial option allows faking initial
migrations. In 1.7, initial migrations were always automatically faked if all
tables created in an initial migration already existed.

An app without migrations with a ForeignKey to an app with migrations
may now result in a foreign key constraint error when migrating the database
or running tests. In Django 1.7, this could fail silently and result in a
missing constraint. To resolve the error, add migrations to the app without
them.

Django 1.6 introduced {%loadcyclefromfuture%} and
{%loadfirstoffromfuture%} syntax for forward compatibility of the
cycle and firstof template tags. This syntax is now deprecated
and will be removed in Django 1.10. You can simply remove the
{%load...fromfuture%} tags.

In the olden days of Django, it was encouraged to reference views as strings
in urlpatterns:

urlpatterns=patterns('',url('^$','myapp.views.myview'),)

and Django would magically import myapp.views.myview internally and turn
the string into a real function reference. In order to reduce repetition when
referencing many views from the same module, the patterns() function takes
a required initial prefix argument which is prepended to all
views-as-strings in that set of urlpatterns:

In the modern era, we have updated the tutorial to instead recommend importing
your views module and referencing your view functions (or classes) directly.
This has a number of advantages, all deriving from the fact that we are using
normal Python in place of “Django String Magic”: the errors when you mistype a
view name are less obscure, IDEs can help with autocompletion of view names,
etc.

So these days, the above use of the prefix arg is much more likely to be
written (and is better written) as:

Thus patterns() serves little purpose and is a burden when teaching new users
(answering the newbie’s question “why do I need this empty string as the first
argument to patterns()?”). For these reasons, we are deprecating it.
Updating your code is as simple as ensuring that urlpatterns is a list of
django.conf.urls.url() instances. For example:

Reversing URLs by Python path is an expensive operation as it causes the
path being reversed to be imported. This behavior has also resulted in a
security issue. Use named URL patterns
for reversing instead.

The django.db.models.sql.aggregates and
django.contrib.gis.db.models.sql.aggregates modules (both private API), have
been deprecated as django.db.models.aggregates and
django.contrib.gis.db.models.aggregates are now also responsible
for SQL generation. The old modules will be removed in Django 1.10.

If you were using the old modules, see Query Expressions for instructions on rewriting custom aggregates
using the new stable API.

The following methods and properties of django.db.models.sql.query.Query
have also been deprecated and the backwards compatibility shims will be removed
in Django 1.10:

Management commands now use argparse instead of optparse to
parse command-line arguments passed to commands. This also means that the way
to add custom arguments to commands has changed: instead of extending the
option_list class list, you should now override the
add_arguments() method and add
arguments through argparse.add_argument(). See
this example for more details.

The --list option of the migrate management command is
deprecated and will be removed in Django 1.10. Use showmigrations
instead.

cache_choices option of ModelChoiceField and ModelMultipleChoiceField¶

ModelChoiceField and
ModelMultipleChoiceField took an undocumented, untested
option cache_choices. This cached querysets between multiple renderings of
the same Form object. This option is subject to an accelerated deprecation
and will be removed in Django 1.9.

django.utils.html.remove_tags() as well as the template filter
removetags have been deprecated as they cannot guarantee safe output. Their
existence is likely to lead to their use in security-sensitive contexts where
they are not actually safe.

The unused and undocumented django.utils.html.strip_entities() function has
also been deprecated.

django.db.models.fields.subclassing.SubfieldBase has been deprecated and
will be removed in Django 1.10. Historically, it was used to handle fields where
type conversion was needed when loading from the database, but it was not used
in .values() calls or in aggregates. It has been replaced with
from_db_value().

The new approach doesn’t call the to_python()
method on assignment as was the case with SubfieldBase. If you need that
behavior, reimplement the Creator class from Django’s source code
in your project.

The django.utils.checksums module has been deprecated and will be removed
in Django 1.10. The functionality it provided (validating checksum using the
Luhn algorithm) was undocumented and not used in Django. The module has been
moved to the django-localflavor package (version 1.1+).

The original_content_type_id attribute on InlineAdminForm has been
deprecated and will be removed in Django 1.10. Historically, it was used
to construct the “view on site” URL. This URL is now accessible using the
absolute_url attribute of the form.

Both classes provide a render() method, however, the former takes a
django.template.Context as an argument while the latter expects a
dict. This change is enforced through a deprecation path for Django
templates.

Storage subclasses should add max_length=None as a parameter to
get_available_name() and/or
save() if they override either method.
Support for storages that do not accept this argument will be removed in
Django 1.10.

In previous Django versions, various internal ORM methods (mostly as_sql
methods) accepted a qn (for “quote name”) argument, which was a reference
to a function that quoted identifiers for sending to the database. In Django
1.8, that argument has been renamed to compiler and is now a full
SQLCompiler instance. For backwards-compatibility, calling a
SQLCompiler instance performs the same name-quoting that the qn
function used to. However, this backwards-compatibility shim is immediately
deprecated: you should rename your qn arguments to compiler, and call
compiler.quote_name_unless_alias(...) where you previously called
qn(...).

Using AuthenticationMiddleware without SessionAuthenticationMiddleware¶

django.contrib.auth.middleware.SessionAuthenticationMiddleware was
added in Django 1.7. In Django 1.7.2, its functionality was moved to
auth.get_user() and, for backwards compatibility, enabled only if
'django.contrib.auth.middleware.SessionAuthenticationMiddleware' appears in
MIDDLEWARE_CLASSES.

In Django 1.10, session verification will be enabled regardless of whether or not
SessionAuthenticationMiddleware is enabled (at which point
SessionAuthenticationMiddleware will have no significance). You can add it
to your MIDDLEWARE_CLASSES sometime before then to opt-in. Please read the
upgrade considerations first.

Private attribute django.db.models.Field.related is deprecated in favor
of Field.rel. The latter is an instance of
django.db.models.fields.related.ForeignObjectRel which replaces
django.db.models.related.RelatedObject. The django.db.models.related
module has been removed and the Field.related attribute will be removed in
Django 1.10.

The ssi template tag allows files to be included in a template by
absolute path. This is of limited use in most deployment situations, and
the include tag often makes more sense. This tag is now deprecated and
will be removed in Django 1.10.

The collect(), extent(), extent3d(), make_line(), and
unionagg() aggregate methods are deprecated and should be replaced by their
function-based aggregate equivalents (Collect, Extent, Extent3D,
MakeLine, and Union).

The backward compatible shims introduced to rename get_query_set
and similar queryset methods are removed. This affects the following classes:
BaseModelAdmin, ChangeList, BaseCommentNode,
GenericForeignKey, Manager, SingleRelatedObjectDescriptor and
ReverseSingleRelatedObjectDescriptor.

The backward compatible shims introduced to rename the attributes
ChangeList.root_query_set and ChangeList.query_set are removed.

django.views.defaults.shortcut and django.conf.urls.shortcut are
removed.

Support for the Python Imaging Library (PIL) module is removed.

The following private APIs are removed:

django.db.backend

django.db.close_connection()

django.db.backends.creation.BaseDatabaseCreation.set_autocommit()

django.db.transaction.is_managed()

django.db.transaction.managed()

django.forms.widgets.RadioInput is removed.

The module django.test.simple and the class
django.test.simple.DjangoTestSuiteRunner are removed.

The module django.test._doctest is removed.

The CACHE_MIDDLEWARE_ANONYMOUS_ONLY setting is removed. This change
affects both django.middleware.cache.CacheMiddleware and
django.middleware.cache.UpdateCacheMiddleware despite the lack of a
deprecation warning in the latter class.

Usage of the hard-coded Hold down “Control”, or “Command” on a Mac, to select
more than one. string to override or append to user-provided help_text in
forms for ManyToMany model fields is not performed by Django anymore
either at the model or forms layer.

The Model._meta.get_(add|change|delete)_permission methods are removed.

The session key django_language is no longer read for backwards
compatibility.