May 17, 2010.

Welcome to Django 1.2!

Nearly a year in the making, Django 1.2 packs an impressive list of new features and lots of bug fixes. These release notes cover the new features, as well as important changes you’ll want to be aware of when upgrading from Django 1.1 or older versions.

Again, these are just the big features that will affect the most users. Users upgrading from previous versions of Django are heavily encouraged to consult the complete list of backwards-incompatible changes and the list of deprecated features .

The user_passes_test() , login_required() , and permission_required() , decorators from django.contrib.auth only apply to functions and no longer work on methods. There’s a simple one-line fix detailed below .

The internals of template tags have changed somewhat; authors of custom template tags that need to store state (e.g. custom control flow tags) should ensure that their code follows the new rules for stateful template tags

Authors of custom Field subclasses should be aware that a number of methods have had a change in prototype, detailed under get_db_prep_*() methods on Field , below.

However, upgrading to the new CSRF protection framework requires a few important backwards-incompatible changes, detailed in CSRF Protection , below.

The new CSRF protection framework is not backwards-compatible with the old system. Users of the old system will not be affected until the old system is removed in Django 1.4.

However, a handful of features have changed in ways that, for some users, will be backwards-incompatible. The big changes are:

Wherever possible these features have been introduced in a backwards-compatible manner per our API stability policy policy.

Django Advent covered the release of Django 1.2 with a series of articles and tutorials that cover some of the new features in depth.

These are just the highlights; full details and a complete list of features may be found below .

A roadmap for Django’s overall 2.x Python support, and eventual transition to Python 3.x, is currently being developed, and will be announced prior to the release of Django 1.3.

This change should affect only a small number of Django users, as most operating-system vendors today are shipping Python 2.4 or newer as their default version. If you’re still using Python 2.3, however, you’ll need to stick to Django 1.1 until you can upgrade; per our support policy , Django 1.1 will continue to receive security support until the release of Django 1.3.

While not a new feature, it’s important to note that Django 1.2 introduces the first shift in our Python compatibility policy since Django’s initial public debut. Previous Django releases were tested and supported on 2.x Python versions from 2.3 up; Django 1.2, however, drops official support for Python 2.3. As such, the minimum Python version required for Django is now 2.4, and Django is tested and supported on Python 2.4, 2.5 and 2.6, and will be supported on the as-yet-unreleased Python 2.7.

These are also available in others parts like the date and time template filters, the humanize template tag library and the new format localization framework.

The argument to the now has gained two new format characters: c to specify that a datetime value should be formatted in ISO 8601 format, and u that allows output of the microseconds part of a datetime or time value.

If a user has JavaScript enabled in their browser, the interface for inline objects in the admin now allows inline objects to be dynamically added and removed. Users without JavaScript-enabled browsers will see no change in the behavior of inline objects.

Finally, GeoDjango’s documentation is now included with Django’s and is no longer hosted separately at geodjango.org .

The GDAL interface now allows the user to set a spatial_filter on the features returned when iterating over a Layer .

The GEOS interface was updated to use thread-safe C library functions when available on the platform.

Support for 3D geometry fields was added, and may be enabled by setting the dim keyword to 3 in your GeometryField . The Extent3D aggregate and extent3d() GeoQuerySet method were added as a part of this feature.

GeoDjango now supports the rich capabilities added in the PostGIS 1.5 release. New features include support for the geography type and enabling of distance queries with non-point geometries on geographic coordinate systems.

The most significant new feature for GeoDjango in 1.2 is support for multiple spatial databases. As a result, the following spatial database backends are now included:

Syndication feeds can now be used directly as views in your URLconf . This means that you can maintain complete control over the URL structure of your feeds. Like any other view, feeds views are passed a request object, so you can do anything you would normally do with a view, like user based access control, or making a feed a named URL.

You can now use a DJANGO_COLORS environment variable to modify or disable the colors used by django-admin.py to provide syntax highlighting .

django.contrib.admin.ModelAdmin.readonly_fields has been added to enable non-editable fields in add/change pages for models and inlines. Field and calculated values can be displayed alongside editable fields.

Django’s internationalization framework has been expanded with locale-aware formatting and form processing. That means, if enabled, dates and numbers on templates will be displayed using the format specified for the current locale. Django will also use localized formats when parsing data in forms. See Format localization for more details.

Both the test subcommand of django-admin.py and the runtests.py script used to run Django’s own test suite now support a --failfast option. When specified, this option causes the test runner to exit after encountering a failure instead of continuing with the test run. In addition, the handling of Ctrl-C during a test run has been improved to trigger a graceful exit from the test run that reports details of the tests that were run before the interruption.

Fixtures can now refer to remote objects using Natural keys . This lookup scheme is an alternative to the normal primary-key based object references in a fixture, improving readability and resolving problems referring to objects whose primary key value may not be predictable or known.

If you have developed your own custom template loaders we suggest to consider porting them to a class-based implementation because the code for backwards compatibility with function-based loaders starts its deprecation process in Django 1.2 and will be removed in Django 1.4. There is a description of the API these loader classes must implement in the template API reference and you can also examine the source code of the loaders shipped with Django.

All the template loaders shipped with Django have been ported to the new API but they still implement the function-based API and the template core machinery still accepts function-based loaders (builtin or third party) so there is no immediate need to modify your TEMPLATE_LOADERS setting in existing projects, things will keep working if you leave it untouched up to and including the Django 1.3 release.

As part of the changes made to introduce Template caching and following a general trend in Django, the template loaders API has been modified to use template loading mechanisms that are encapsulated in Python classes as opposed to functions, the only method available until Django 1.1.

In previous versions of Django, every time you rendered a template, it would be reloaded from disk. In Django 1.2, you can use a cached template loader to load templates once, then cache the result for every subsequent render. This can lead to a significant performance improvement if your templates are broken into lots of smaller subtemplates (using the {% extends %} or {% include %} tags).

Also, filters may now be used in the if expression. For example:

The operators supported are == , != , < , > , <= , >= , in and not in , all of which work like the Python operators, in addition to and , or and not , which were already supported.

There’s really no reason to use {% ifequal %} or {% ifnotequal %} anymore, unless you’re the nostalgic type.

The if tag has been upgraded to be much more powerful. First, we’ve added support for comparison operators. No longer will you have to type:

This also makes it easier to debug mail sending. Django ships with backend implementations that allow you to send email to a file , to the console , or to memory . You can even configure all email to be thrown away .

You can now configure the way that Django sends email . Instead of using SMTP to send all email, you can now choose a configurable email backend to send messages. If your hosting provider uses a sandbox or some other non-SMTP technique for sending mail, you can now construct an email backend that will allow Django’s standard mail sending methods to use those facilities.

If you provide a custom auth backend with supports_anonymous_user set to True , AnonymousUser will check the backend for permissions, just like User already did. This is useful for centralizing permission handling - apps can always delegate the question of whether something is allowed or not to the authorization/authentication backend. See the authentication docs for more details.

A foundation for specifying permissions at the per-object level has been added. Although there is no implementation of this in core, a custom authentication backend can provide this implementation and it will be used by django.contrib.auth.models.User . See the authentication docs for more information.

Django now includes a robust and configurable messages framework with built-in support for cookie- and session-based messaging, for both anonymous and authenticated clients. The messages framework replaces the deprecated user message API and allows you to temporarily store messages in one request and retrieve them for display in a subsequent request (usually the next one).

Django now has much improved protection against Cross-Site Request Forgery (CSRF) attacks . This type of attack occurs when a malicious website contains a link, a form button or some JavaScript that is intended to perform some action on your website, using the credentials of a logged-in user who visits the malicious site in their browser. A related type of attack, “login CSRF,” where an attacking site tricks a user’s browser into logging into a site with someone else’s credentials, is also covered.

Model instances now have support for validating their own data , and both model and form fields now accept configurable lists of validators specifying reusable, encapsulated validation behavior. Note, however, that validation must still be performed explicitly. Simply invoking a model instance’s save() method will not perform any validation of the instance’s data.

Django 1.2 adds the ability to use more than one database in your Django project. Queries can be issued at a specific database with the using() method on QuerySet objects. Individual objects can be saved to a specific database by providing a using argument when you call save() .

Backwards-incompatible changes in 1.2¶

Wherever possible the new features above have been introduced in a backwards-compatible manner per our API stability policy policy. This means that practically all existing code which worked with Django 1.1 will continue to work with Django 1.2; such code will, however, begin issuing warnings (see below for details).

However, a handful of features have changed in ways that, for some users, will be immediately backwards-incompatible. Those changes are detailed below.

CSRF Protection¶ We’ve made large changes to the way CSRF protection works, detailed in the CSRF documentation. Here are the major changes you should be aware of: CsrfResponseMiddleware and CsrfMiddleware have been deprecated and will be removed completely in Django 1.4, in favor of a template tag that should be inserted into forms.

All contrib apps use a csrf_protect decorator to protect the view. This requires the use of the csrf_token template tag in the template. If you have used custom templates for contrib views, you MUST READ THE UPGRADE INSTRUCTIONS to fix those templates. Documentation removed The upgrade notes have been removed in current Django docs. Please refer to the docs for Django 1.3 or older to find these instructions.

CsrfViewMiddleware is included in MIDDLEWARE_CLASSES by default. This turns on CSRF protection by default, so views that accept POST requests need to be written to work with the middleware. Instructions on how to do this are found in the CSRF docs.

All of the CSRF has moved from contrib to core (with backwards compatible imports in the old locations, which are deprecated and will cease to be supported in Django 1.4).

get_db_prep_*() methods on Field ¶ Prior to Django 1.2, a custom Field had the option of defining several functions to support conversion of Python values into database-compatible values. A custom field might look something like: class CustomModelField ( models . Field ): # ... def db_type ( self ): # ... def get_db_prep_save ( self , value ): # ... def get_db_prep_value ( self , value ): # ... def get_db_prep_lookup ( self , lookup_type , value ): # ... In 1.2, these three methods have undergone a change in prototype, and two extra methods have been introduced: class CustomModelField ( models . Field ): # ... def db_type ( self , connection ): # ... def get_prep_value ( self , value ): # ... def get_prep_lookup ( self , lookup_type , value ): # ... def get_db_prep_save ( self , value , connection ): # ... def get_db_prep_value ( self , value , connection , prepared = False ): # ... def get_db_prep_lookup ( self , lookup_type , value , connection , prepared = False ): # ... These changes are required to support multiple databases – db_type and get_db_prep_* can no longer make any assumptions regarding the database for which it is preparing. The connection argument now provides the preparation methods with the specific connection for which the value is being prepared. The two new methods exist to differentiate general data-preparation requirements from requirements that are database-specific. The prepared argument is used to indicate to the database-preparation methods whether generic value preparation has been performed. If an unprepared (i.e., prepared=False ) value is provided to the get_db_prep_*() calls, they should invoke the corresponding get_prep_*() calls to perform generic data preparation. We’ve provided conversion functions that will transparently convert functions adhering to the old prototype into functions compatible with the new prototype. However, these conversion functions will be removed in Django 1.4, so you should upgrade your Field definitions to use the new prototype as soon as possible. If your get_db_prep_*() methods made no use of the database connection, you should be able to upgrade by renaming get_db_prep_value() to get_prep_value() and get_db_prep_lookup() to get_prep_lookup() . If you require database specific conversions, then you will need to provide an implementation get_db_prep_* that uses the connection argument to resolve database-specific values.

user_passes_test , login_required and permission_required ¶ django.contrib.auth.decorators provides the decorators login_required , permission_required and user_passes_test . Previously it was possible to use these decorators both on functions (where the first argument is ‘request’) and on methods (where the first argument is ‘self’, and the second argument is ‘request’). Unfortunately, flaws were discovered in the code supporting this: it only works in limited circumstances, and produces errors that are very difficult to debug when it does not work. For this reason, the ‘auto adapt’ behavior has been removed, and if you are using these decorators on methods, you will need to manually apply django.utils.decorators.method_decorator() to convert the decorator to one that works with methods. For example, you would change code from this: class MyClass ( object ): @login_required def my_view ( self , request ): pass to this: from django.utils.decorators import method_decorator class MyClass ( object ): @method_decorator ( login_required ) def my_view ( self , request ): pass or: from django.utils.decorators import method_decorator login_required_m = method_decorator ( login_required ) class MyClass ( object ): @login_required_m def my_view ( self , request ): pass For those of you who’ve been following the development trunk, this change also applies to other decorators introduced since 1.1, including csrf_protect , cache_control and anything created using decorator_from_middleware .

if tag changes¶ Due to new features in the if template tag, it no longer accepts ‘and’, ‘or’ and ‘not’ as valid variable names. Previously, these strings could be used as variable names. Now, the keyword status is always enforced, and template code such as {% if not %} or {% if and %} will throw a TemplateSyntaxError . Also, in is a new keyword and so is not a valid variable name in this tag.

LazyObject ¶ LazyObject is an undocumented-but-often-used utility class used for lazily wrapping other objects of unknown type. In Django 1.1 and earlier, it handled introspection in a non-standard way, depending on wrapped objects implementing a public method named get_all_members() . Since this could easily lead to name clashes, it has been changed to use the standard Python introspection method, involving __members__ and __dir__() . If you used LazyObject in your own code and implemented the get_all_members() method for wrapped objects, you’ll need to make a couple of changes: First, if your class does not have special requirements for introspection (i.e., you have not implemented __getattr__() or other methods that allow for attributes not discoverable by normal mechanisms), you can simply remove the get_all_members() method. The default implementation on LazyObject will do the right thing. If you have more complex requirements for introspection, first rename the get_all_members() method to __dir__() . This is the standard introspection method for Python 2.6 and above. If you require support for Python versions earlier than 2.6, add the following code to the class: __members__ = property ( lambda self : self . __dir__ ())

__dict__ on model instances¶ Historically, the __dict__ attribute of a model instance has only contained attributes corresponding to the fields on a model. In order to support multiple database configurations, Django 1.2 has added a _state attribute to object instances. This attribute will appear in __dict__ for a model instance. If your code relies on iterating over __dict__ to obtain a list of fields, you must now be prepared to handle or filter out the _state attribute.

Test runner exit status code¶ The exit status code of the test runners ( tests/runtests.py and python manage.py test ) no longer represents the number of failed tests, because a failure of 256 or more tests resulted in a wrong exit status code. The exit status code for the test runner is now 0 for success (no failing tests) and 1 for any number of test failures. If needed, the number of test failures can be found at the end of the test runner’s output.

Cookie encoding¶ To fix bugs with cookies in Internet Explorer, Safari, and possibly other browsers, our encoding of cookie values was changed so that the comma and semicolon are treated as non-safe characters, and are therefore encoded as \054 and \073 respectively. This could produce backwards incompatibilities, especially if you are storing comma or semi-colon in cookies and have JavaScript code that parses and manipulates cookie values client-side.

ModelForm.is_valid() and ModelForm.errors ¶ Much of the validation work for ModelForms has been moved down to the model level. As a result, the first time you call ModelForm.is_valid() , access ModelForm.errors or otherwise trigger form validation, your model will be cleaned in-place. This conversion used to happen when the model was saved. If you need an unmodified instance of your model, you should pass a copy to the ModelForm constructor.

BooleanField on MySQL¶ In previous versions of Django, a model’s BooleanField under MySQL would return its value as either 1 or 0 , instead of True or False ; for most people this wasn’t a problem because bool is a subclass of int in Python. In Django 1.2, however, BooleanField on MySQL correctly returns a real bool . The only time this should ever be an issue is if you were expecting the repr of a BooleanField to print 1 or 0 .

Changes to the interpretation of max_num in FormSets¶ As part of enhancements made to the handling of FormSets, the default value and interpretation of the max_num parameter to the django.forms.formsets.formset_factory() and django.forms.models.modelformset_factory() functions has changed slightly. This change also affects the way the max_num argument is used for inline admin objects. Previously, the default value for max_num was 0 (zero). FormSets then used the boolean value of max_num to determine if a limit was to be imposed on the number of generated forms. The default value of 0 meant that there was no default limit on the number of forms in a FormSet. Starting with 1.2, the default value for max_num has been changed to None , and FormSets will differentiate between a value of None and a value of 0 . A value of None indicates that no limit on the number of forms is to be imposed; a value of 0 indicates that a maximum of 0 forms should be imposed. This doesn’t necessarily mean that no forms will be displayed – see the ModelFormSet documentation for more details. If you were manually specifying a value of 0 for max_num , you will need to update your FormSet and/or admin definitions. See also JavaScript-assisted handling of inline related objects in the admin