This page documents release notes for the as-yet-unreleased Django 1.4. As such, it’s tentative and subject to change. It provides up-to-date information for those who are following trunk.
Django 1.4 includes various new features and some minor backwards incompatible changes. There are also some features that have been dropped, which are detailed in our deprecation plan, and we’ve begun the deprecation process for some features.
While not a new feature, it’s important to note that Django 1.4 introduces the second shift in our Python compatibility policy since Django’s initial public debut. Django 1.2 dropped support for Python 2.3; now Django 1.4 drops support for Python 2.4. As such, the minimum Python version required for Django is now 2.5, and Django is tested and supported on Python 2.5, 2.6 and 2.7.
This change should affect only a small number of Django users, as most operating-system vendors today are shipping Python 2.5 or newer as their default version. If you’re still using Python 2.4, however, you’ll need to stick to Django 1.3 until you can upgrade; per our support policy, Django 1.3 will continue to receive security support until the release of Django 1.5.
Django does not support Python 3.x at this time. A document outlining our full timeline for deprecating Python 2.x and moving to Python 3.x will be published before the release of Django 1.4.
Django 1.4 now includes a QuerySet.select_for_update() method which generates a SELECT ... FOR UPDATE SQL query. This will lock rows until the end of the transaction, meaning that other transactions cannot modify or delete rows matched by a FOR UPDATE query.
For more details, see the documentation for select_for_update().
This method allows for more efficient creation of multiple objects in the ORM. It can provide significant performance increases if you have many objects, Django makes use of this internally, meaning some operations (such as database setup for test suites) has seen a performance benefit as a result.
See the bulk_create() docs for more information.
We’ve switched the admin and other bundled templates to use the HTML5 doctype. While Django will be careful in its use of HTML5 features, to maintain compatibility with older browsers, this change means that you can use any HTML5 features you need in admin pages without having to lose HTML validity or override the provided templates to change the doctype.
Django hasn’t had a clear policy on which browsers are supported for using the admin app. Django’s new policy formalizes existing practices: YUI’s A-grade browsers should provide a fully-functional admin experience, with the notable exception of IE6, which is no longer supported.
Released over ten years ago, IE6 imposes many limitations on modern web development. The practical implications of this policy are that contributors are free to improve the admin without consideration for these limitations.
This new policy has no impact on development outside of the admin. Users of Django are free to develop webapps compatible with any range of browsers.
Prior to Django 1.4, the Django admin app allowed specifying change list filters by specifying a field lookup (including spanning relations), and not custom filters. This has been rectified with a simple API previously known as “FilterSpec” which was used internally. For more details, see the documentation for list_filter.
The admin change list now supports sorting on multiple columns. It respects all elements of the ordering attribute, and sorting on multiple columns by clicking on headers is designed to work similarly to how desktop GUIs do it. The new hook get_ordering() for specifying the ordering dynamically (e.g. depending on the request) has also been added.
Django 1.4 adds both a low-level API for signing values and a high-level API for setting and reading signed cookies, one of the most common uses of signing in Web applications.
See cryptographic signing docs for more information.
Django 1.4 introduces a new cookie based backend for the session framework which uses the tools for cryptographic signing to store the session data in the client’s browser.
See the cookie-based backend docs for more information.
The previously shipped FormWizard of the formtools contrib app has been replaced with a new implementation that is based on the class based views introduced in Django 1.3. It features a pluggable storage API and doesn’t require the wizard to pass around hidden fields for every previous step.
Django 1.4 ships with a session based storage backend and a cookie based storage backend. The latter uses the tools for cryptographic signing also introduced in Django 1.4 to store the wizard state in the user’s cookies.
See the form wizard docs for more information.
A lazily evaluated version of django.core.urlresolvers.reverse() was added to allow using URL reversals before the project’s URLConf gets loaded.
Django 1.4 gained the ability to look for a language prefix in the URL pattern when using the new django.conf.urls.i18n.i18n_patterns() helper function. Additionally, it’s now possible to define translatable URL patterns using ugettext_lazy(). See Specifying translation strings: In URL patterns for more information about the language prefix and how to internationalize URL patterns.
Two new attributes, pk_url_kwarg and slug_url_kwarg, have been added to django.views.generic.detail.SingleObjectMixin to enable the customization of URLConf keyword arguments used for single object generic views.
A new helper function, assignment_tag, was added to template.Library to ease the creation of template tags that store some data in a specified context variable.
simple_tag, inclusion_tag and the newly introduced assignment_tag template helper functions may now accept any number of positional or keyword arguments. For example:
@register.simple_tag
def my_tag(a, b, *args, **kwargs):
warning = kwargs['warning']
profile = kwargs['profile']
...
return ...
Then in the template any number of arguments may be passed to the template tag. For example:
{% my_tag 123 "abcd" book.title warning=message|lower profile=user.profile %}
In previous versions of Django, whenever the TEMPLATE_DEBUG setting was True, any exception raised during template rendering (even exceptions unrelated to template syntax) were wrapped in TemplateSyntaxError and re-raised. This was done in order to provide detailed template source location information in the debug 500 page.
In Django 1.4, exceptions are no longer wrapped. Instead, the original exception is annotated with the source information. This means that catching exceptions from template rendering is now consistent regardless of the value of TEMPLATE_DEBUG, and there's no need to catch and unwrap TemplateSyntaxError in order to catch other errors.
Added a filter which truncates a string to be no longer than the specified number of characters. Truncated strings end with a translatable ellipsis sequence ("..."). See the truncatechars docs for more details.
The staticfiles contrib app has now a new static template tag to refer to files saved with the STATICFILES_STORAGE storage backend. It'll use the storage url method and therefore supports advanced features such as serving files from a cloud service.
Additional to the static template tag the staticfiles contrib app now has a CachedStaticFilesStorage which caches the files it saves (when running the collectstatic management command) by appending the MD5 hash of the file's content to the filename. For example, the file css/styles.css would also be saved as css/styles.55e7cbb9ba48.css
See the CachedStaticFilesStorage docs for more information.
We've added a middleware to provide easy protection against clickjacking using the X-Frame-Options header. It's not enabled by default for backwards compatibility reasons, but you'll almost certainly want to enable it to help plug that security hole for browsers that support the header.
We've made various improvements to our CSRF features, including the ensure_csrf_cookie() decorator which can help with AJAX heavy sites, protection for PUT and DELETE, and settings CSRF_COOKIE_SECURE and CSRF_COOKIE_PATH which can improve the security and usefulness of the CSRF protection. See the CSRF docs for more information.
Two new function decorators, sensitive_variables() and sensitive_post_parameters(), were added to allow designating the traceback frames' local variables and request's POST parameters susceptible to contain sensitive information and that should be filtered out of error reports.
All POST parameters are now systematically filtered out of error reports for certain contrib.views.auth views (login, password_reset_confirm, password_change, and add_view and user_change_password in the auth admin) to prevent the leaking of sensitive information such as user passwords.
You may override or customize the default filtering by writing a custom filter. Learn more on Filtering error reports.
The previously added support for IPv6 addresses when using the runserver management command in Django 1.3 has now been further extended by adding a GenericIPAddressField model field, a GenericIPAddressField form field and the validators validate_ipv46_address and validate_ipv6_address
Django 1.4 also includes several smaller improvements worth noting:
A more usable stacktrace in the technical 500 page: frames in the stack trace which reference Django's code are dimmed out, while frames in user code are slightly emphasized. This change makes it easier to scan a stacktrace for issues in user code.
Customizable names for simple_tag().
In the documentation, a helpful security overview page.
Function django.contrib.auth.models.check_password() has been moved to the django.contrib.auth.utils module. Importing it from the old location will still work, but you should update your imports.
The collectstatic management command gained a --clear option to delete all files at the destination before copying or linking the static files.
It is now possible to load fixtures containing forward references when using MySQL with the InnoDB database engine.
A new 403 response handler has been added as 'django.views.defaults.permission_denied'. You can set your own handler by setting the value of django.conf.urls.handler403. See the documentation about the 403 (HTTP Forbidden) view for more information.
The trans template tag now takes an optional as argument to be able to retrieve a translation string without displaying it but setting a template context variable instead.
A new plain text version of the HTTP 500 status code internal error page served when DEBUG is True is now sent to the client when Django detects that the request has originated in JavaScript code (is_ajax() is used for this).
Similarly to its HTML counterpart, it contains a collection of different pieces of information about the state of the web application.
This should make it easier to read when debugging interaction with client-side Javascript code.
The included administration app django.contrib.admin has for a long time shipped with a default set of static files such as JavaScript, images and stylesheets. Django 1.3 added a new contrib app django.contrib.staticfiles to handle such files in a generic way and defined conventions for static files included in apps.
Starting in Django 1.4 the admin's static files are now also following this convention to make it easier to deploy the included files. In previous versions of Django, it was also common to define a ADMIN_MEDIA_PREFIX setting to point to the URL where the admin's static files are served by a web server. This setting has now been deprecated and replaced by the more general setting STATIC_URL. Django will now expect to find the admin static files under the URL <STATIC_URL>/admin/.
If you've previously used a URL path for ADMIN_MEDIA_PREFIX (e.g. /media/) simply make sure STATIC_URL and STATIC_ROOT are configured and your web server serves the files correctly. The development server continues to serve the admin files just like before. Don't hesitate to consult the static files howto for further details.
In case your ADMIN_MEDIA_PREFIX is set to an own domain (e.g. http://media.example.com/admin/) make sure to also set your STATIC_URL setting to the correct URL, for example http://media.example.com/.
Warning
If you're implicitely relying on the path of the admin static files on your server's file system when you deploy your site, you have to update that path. The files were moved from django/contrib/admin/media/ to django/contrib/admin/static/admin/.
As part of an effort to improve the performance and usability of the admin's changelist sorting interface and of the admin's horizontal and vertical "filter" widgets, some icon files were removed and grouped into two sprite files, respectively: selector-add.gif, selector-addall.gif, selector-remove.gif, selector-removeall.gif, selector_stacked-add.gif and selector_stacked-remove.gif into selector-icons.gif; and arrow-up.gif and arrow-down.gif into sorting-icons.gif. If you used those icons to customize the admin then you will want to replace them with your own icons or retrieve them from a previous release.
Django 1.3 changed the cryptographic signing mechanisms used in a number of places in Django. While Django 1.3 kept fallbacks that would accept hashes produced by the previous methods, these fallbacks are removed in Django 1.4.
So, if you upgrade to Django 1.4 directly from 1.2 or earlier, you may lose/invalidate certain pieces of data that have been cryptographically signed using an old method. To avoid this, use Django 1.3 first, for a period of time, to allow the signed data to expire naturally. The affected parts are detailed below, with 1) the consequences of ignoring this advice and 2) the amount of time you need to run Django 1.3 for the data to expire or become irrelevant.
Form related hashes — these are much shorter lifetime, and are relevant only for the short window where a user might fill in a form generated by the pre-upgrade Django instance, and try to submit it to the upgraded Django instance:
Starting in the 1.4 release the FlatpageFallbackMiddleware only adds a trailing slash and redirects if the resulting URL refers to an existing flatpage. For example, requesting /notaflatpageoravalidurl in a previous version would redirect to /notaflatpageoravalidurl/, which would subsequently raise a 404. Requesting /notaflatpageoravalidurl now will immediately raise a 404. Additionally redirects returned by flatpages are now permanent (301 status code) to match the behavior of the CommonMiddleware.
Django's comments app has historically supported excluding the comments of a special user group, but we've never documented the feature properly and didn't enforce the exclusion in other parts of the app, e.g., the template tags. To fix this problem, we removed the code from the feed class.
If you rely on the feature and want to restore the old behavior, simply use a custom comment model manager to exclude the user group, like this:
from django.conf import settings
from django.contrib.comments.managers import CommentManager
class BanningCommentManager(CommentManager):
def get_query_set(self):
qs = super(BanningCommentManager, self).get_query_set()
if getattr(settings, 'COMMENTS_BANNED_USERS_GROUP', None):
where = ['user_id NOT IN (SELECT user_id FROM auth_user_groups WHERE group_id = %s)']
params = [settings.COMMENTS_BANNED_USERS_GROUP]
qs = qs.extra(where=where, params=params)
return qs
Save this model manager in your custom comment app (e.g. in my_comments_app/managers.py) and add it your custom comment app model:
from django.db import models
from django.contrib.comments.models import Comment
from my_comments_app.managers import BanningCommentManager
class CommentWithTitle(Comment):
title = models.CharField(max_length=300)
objects = BanningCommentManager()
For more details, see the documentation about customizing the comments framework.
Django can report 404 errors: see Error reporting. Until Django 1.3, it was possible to exclude some URLs from the reporting by adding prefixes to IGNORABLE_404_STARTS and suffixes to IGNORABLE_404_ENDS.
In Django 1.4, these two settings are superseded by IGNORABLE_404_URLS, which is a list of compiled regular expressions. Django won't send an email for 404 errors on URLs that match any of them.
Furthermore, the previous settings had some rather arbitrary default values:
IGNORABLE_404_STARTS = ('/cgi-bin/', '/_vti_bin', '/_vti_inf')
IGNORABLE_404_ENDS = ('mail.pl', 'mailform.pl', 'mail.cgi', 'mailform.cgi',
'favicon.ico', '.php')
It's not Django's role to decide if your website has a legacy /cgi-bin/ section or a favicon.ico. As a consequence, the default values of IGNORABLE_404_URLS, IGNORABLE_404_STARTS and IGNORABLE_404_ENDS are all now empty.
If you have customized IGNORABLE_404_STARTS or IGNORABLE_404_ENDS, or if you want to keep the old default value, you should add the following lines in your settings file:
import re
IGNORABLE_404_URLS = (
# for each <prefix> in IGNORABLE_404_STARTS
re.compile(r'^<prefix>'),
# for each <suffix> in IGNORABLE_404_ENDS
re.compile(r'<suffix>$'),
)
Don't forget to escape characters that have a special meaning in a regular expression.
Previously, Django's CSRF protection provided protection against only POST requests. Since use of PUT and DELETE methods in AJAX applications is becoming more common, we now protect all methods not defined as safe by RFC 2616 i.e. we exempt GET, HEAD, OPTIONS and TRACE, and enforce protection on everything else.
If you using PUT or DELETE methods in AJAX applications, please see the instructions about using AJAX and CSRF.
This was an alias to django.template.loader since 2005, it has been removed without emitting a warning due to the length of the deprecation. If your code still referenced this please use django.template.loader instead.
This functionality has been removed due to intractable performance and security issues. Any existing usage of verify_exists should be removed.
The open method of the base Storage class took an obscure parameter mixin which allowed to dynamically change the base classes of the returned file object. In the rare case you relied on the mixin parameter, you can easily achieve the same by overriding the open method, e.g.:
from django.core.files import File
from django.core.files.storage import FileSystemStorage
class Spam(File):
"""
Spam, spam, spam, spam and spam.
"""
def ham(self):
return 'eggs'
class SpamStorage(FileSystemStorage):
"""
A custom file storage backend.
"""
def open(self, name, mode='rb'):
return Spam(open(self.path(name), mode))
Some legacy ways of calling cache_page() have been deprecated, please see the docs for the correct way to use this decorator.
Django 1.3 dropped support for PostgreSQL versions older than 8.0 and the relevant documents suggested to use a recent version because of performance reasons but more importantly because end of the upstream support periods for releases 8.0 and 8.1 was near (November 2010.)
Django 1.4 takes that policy further and sets 8.2 as the minimum PostgreSQL version it officially supports.
When logging support was added to Django in 1.3, the admin error email support was moved into the django.utils.log.AdminEmailHandler, attached to the 'django.request' logger. In order to maintain the established behavior of error emails, the 'django.request' logger was called only when DEBUG was False.
To increase the flexibility of request-error logging, the 'django.request' logger is now called regardless of the value of DEBUG, and the default settings file for new projects now includes a separate filter attached to django.utils.log.AdminEmailHandler to prevent admin error emails in DEBUG mode:
'filters': {
'require_debug_false': {
'()': 'django.utils.log.RequireDebugFalse'
}
},
'handlers': {
'mail_admins': {
'level': 'ERROR',
'filters': ['require_debug_false'],
'class': 'django.utils.log.AdminEmailHandler'
}
},
If your project was created prior to this change, your LOGGING setting will not include this new filter. In order to maintain backwards-compatibility, Django will detect that your 'mail_admins' handler configuration includes no 'filters' section, and will automatically add this filter for you and issue a pending-deprecation warning. This will become a deprecation warning in Django 1.5, and in Django 1.6 the backwards-compatibility shim will be removed entirely.
The existence of any 'filters' key under the 'mail_admins' handler will disable this backward-compatibility shim and deprecation warning.
Until Django 1.3 the functions include(), patterns() and url() plus handler404, handler500 were located in a django.conf.urls.defaults module.
Starting with Django 1.4 they are now available in django.conf.urls.
Databrowse has not seen active development for some time, and this does not show any sign of changing. There had been a suggestion for a GSOC project to integrate the functionality of databrowse into the admin, but no progress was made. While Databrowse has been deprecated, an enhancement of django.contrib.admin providing a similar feature set is still possible.
The code that powers Databrowse is licensed under the same terms as Django itself, and so is available to be adopted by an individual or group as a third-party project.
Oct 05, 2011