======================== Porting 0.96 apps to 1.0 ======================== Version 1.0 breaks compatibility with 0.96. This guide will help you port 0.96 projects and apps to 1.0. The first part of this document includes the common changes needed to run with 1.0. If after going through the first part your code still breaks, check the section `Other Changes`_ for a list of all compatibility issues. Common Changes ============== models ------ * The ``maxlength`` argument for model fields was replaced with ``max_length``. * Rename your model's ``__str__`` function to ``__unicode__`` and use unicode strings: ``u'foo'`` instead of ``'foo'``. * The ``prepopulated_from`` argument for model fields has been moved to the ``AdminModel`` class in admin.py (see below). * All of the Admin definitions moved from the ``Model`` definition to the new ``AdminModel`` class stored in an admin.py file. You can read about the new class in `The Django admin site`_. Here is an example with some of the most common changes:: # 0.96: class Author(models.Model): first_name = models.CharField(maxlength=30) last_name = models.CharField(maxlength=30) slug = models.CharField(max_length=60, prepopulate_from=('first_name', 'last_name')) class Admin: fields = ( ('full name', {'fields': ('first_name','last_name'), 'classes': 'collapse wide'}), ) js = ( "/static/my_code.js", ) class Book(models.Model): author = models.ForeignKey(Author, edit_inline=models.TABULAR) title = models.CharField(maxlength=100) # 1.0: class Author(models.Model): first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) class Book(models.Model): author = models.ForeignKey(Author) title = models.CharField(max_length=100) # admin.py from django.contrib import admin from models import Book, Author class BookInline(admin.TabularInline): model = Book extra = 3 class AuthorAdmin(admin.ModelAdmin): inlines = [BookInline] fieldsets = ( ('full name', {'fields': ('first_name','last_name'), 'classes': ('collapse', 'wide')}), ) prepopulated_fields = {'slug': ('first_name', 'last_name')} class Media: js = ( "/static/my_code.js", ) admin.site.register(Author, AuthorAdmin) NOTE: There is a script_ that your models.py and automatically outputs the corresponding source code for admin.py. .. _The Django admin site: http://docs.djangoproject.com/en/dev/ref/contrib/admin/ .. _script: http://www.djangosnippets.org/snippets/603/ Templates --------- * By default the templating system automatically escapes the output of every variable tag. To learn more take a look at `automatic html escaping`_. To disable auto-escaping for an individual variable, use the safe filter:: This will be escaped: {{ data }} This will not be escaped: {{ data|safe }} To disable auto-escaping for an entire template, wrap the template (or just a particular section of the template) in the autoescape tag, like so:: {% autoescape off %} ... normal template content here ... {% endautoescape %} .. _automatic html escaping: http://docs.djangoproject.com/en/dev/topics/templates/#automatic-html-escaping urls ---- * If you are using the Admin you need to update your root ``urls.py``:: # 0.96: from django.conf.urls.defaults import * urlpatterns = patterns('', (r'^admin/', include('django.contrib.admin.urls')), ) # 1.0: from django.conf.urls.defaults import * from django.contrib import admin # automatically load the INSTALLED_APPS admin.py modules admin.autodiscover() urlpatterns = patterns('', (r'^admin/doc/', include('django.contrib.admindocs.urls')), (r'^admin/(.*)', admin.site.root), ) views ----- * With 1.0 ``newforms`` were renamed ``forms`` and ``oldforms`` were removed. If you are already using new forms all you have to do is change your import statement:: # 0.96 from django import newforms as forms # 1.0 from django import forms If you are using the old forms, you will have to rewrite your forms - a good place to start is the `forms documentation`_. .. _forms documentation: http://docs.djangoproject.com/en/dev/topics/forms/ * In 0.96 uploaded files -- that is, entries in ``request.FILES`` -- were represented by simple dictionaries with a few well-known keys. Uploaded files are now represented by an `UploadedFile object`_, and thus the file's information is accessible through object attributes. Thus, given ``f = request.FILES['file_field_name']``: ===================== ===================== 0.96 1.0 ===================== ===================== ``f['content']`` ``f.read()`` ``f['filename']`` ``f.name`` ``f['content-type']`` ``f.content_type`` ===================== ===================== .. _UploadedFile object: http://docs.djangoproject.com/en/dev/topics/http/file-uploads/#uploadedfile-objects Signals ------- * All handlers now must be declared as accepting ``**kwargs``. * Signals are now instances of ``django.dispatch.Signal`` instead of anonymous objects. * Connecting, disconnecting, and sending signals are done via methods on the ``Signal`` object instead of through module methods in ``django.dispatch.dispatcher``. The module-level methods are deprecated. * The ``Anonymous`` and ``Any`` sender options no longer exist. You can still receive signals sent by any sender by using ``sender=None`` * So, a quick summary of the code changes you'd need to make: ========================================================= ================================================ 0.96 1.0 ========================================================= ================================================ ``def my_handler(sender)`` ``def my_handler(sender, **kwargs)`` ``my_signal = object()`` ``my_signal = django.dispatch.Signal()`` ``dispatcher.connect(my_handler, my_signal)`` ``my_signal.connect(my_handler)`` ``dispatcher.send(my_signal, sender)`` ``my_signal.send(sender)`` ``dispatcher.connect(my_handler, my_signal, sender=Any)`` ``my_signal.connect(my_handler, sender=None)`` ========================================================= ================================================ .. Other Changes_: Other Changes ============= * The spaceless template tag removes *all* spaces between HTML tags instead of preserving a single space * ``localflavor.usa`` has been renamed ``localflavor.us``. This change was made to match the naming scheme of other local flavors. * Renamed ``SeesionBase.get_new_session_key() to ``_get_new_session_key()`` and ``removed get_new_session_object()``. * Fixture behaviour has changed slightly: previously, loading a row automatically ran the model's ``save()`` method. This is no longer the case, so any fields (for example: timestamps) that were auto-populated by a ``save()`` now need explicit values in any fixture. * Settings exception changed. ``EnvironmentError`` was split into an ``ImportError`` raised when Django fails to find the settings module and ``RuntimeError`` when you try to reconfigure settings after having already used them * The models manager now returns a ``MultipleObjectsReturned`` exception instead of ``AssertionError``:: #0.96 try: Model.objects.get(...) except AssertionError: ... #1.0 try: Model.objects.get(...) except Model.MultipleObjectsReturned: ... * The manager option to class ``Admin`` no longer exists. In favor of this option, a ``ModelAdmin`` class may now define a queryset method:: class BookAdmin(admin.ModelAdmin): def queryset(self, request): """ Filter based on the current user. """ return self.model._default_manager.filter(user=request.user) * ``django.views.i18n.set_language`` requires a POST request. Previously, a GET request was used. The old behavior meant that state (the locale used to display the site) could be changed by a GET request, which is against the HTTP specification's recommendations. Code calling this view must ensure that a POST request is now made, instead of a GET. This means you can no longer use a link to access the view, but must use a form submission of some kind (e.g. a button). * ``django.http.HttpResponse.headers`` has been renamed to ``_headers`` and ``HttpResponse`` now supports containment checking directly:: # 0.96 if header in response.headers: # 1.0 if header in response: * The generic relation classes - ``GenericForeignKey`` and ``GenericRelation`` - have moved into the ``django.contrib.contenttypes module``:: #0.96 generic_field = models.GenericRelation(SomeOtherModel) #1.0 from django.contrib.contenttypes import generic ... generic_field = generic.GenericRelation(SomeOtherModel) * ``_()`` no longer in builtins so if you were previously relying on ``_()`` always being present, you should now explicitly import ``ugettext`` or ``ugettext_lazy``, if appropriate, and alias it to _ yourself:: from django.utils.translation import ugettext as _ * The ``LazyDate`` helper class was removed. Default field values and query arguments can both be callable objects, so instances of ``LazyDate`` can be replaced with a reference to datetime.now:: # 0.96 class Article(models.Model): title = models.CharField(maxlength=100) published = models.DateField(default=LazyDate()) # 1.0 from datetime import datetime class Article(models.Model): title = models.CharField(maxlength=100) published = models.DateField(default=datetime.now) * The ``LOGIN_URL`` constant moved from ``django.contrib.auth`` into the ``settings`` module. Instead of using ``from django.contrib.auth import LOGIN_URL`` refer to ``settings.LOGIN_URL``. * Test client login method changed:: # 0.96 from django.test import Client c = Client() c.login('/path/to/login','myuser','mypassword') # 1.0 ... c.login(username='myuser', password='mypassword') * Changes to ``django.core.management`` - calls to management services in your code will need to use the ``call_command``. For example, if you have some test code that calls flush and load_data:: from django.core import management management.flush(verbosity=0, interactive=False) management.load_data(['test_data'], verbosity=0) You will need to change this code to read:: from django.core import management management.call_command('flush', verbosity=0, interactive=False) management.call_command('loaddata', 'test_data', verbosity=0) * ``django-admin.py`` and ``manage.py`` now require subcommands to precede options:: django-admin.py --settings=foo.bar runserver changed to:: django-admin.py runserver --settings=foo.bar * Changed ``__init__()`` parameters in syndication framework's Feed class to take an ``HttpRequest`` object as its second parameter, instead of the feed's URL. This allows the syndication framework to work without requiring the sites framework. This only affects code that subclass Feed and overrides the ``__init__()`` method, and code that calls ``Feed.__init__()`` directly. * ``django.newforms.forms.SortedDictFromList`` class removed, due to ``django.utils.datastructures.SortedDict`` gaining the ability to be instantiated with a sequence of tuples. Two things need to be done to fix your code: 1. Use ``django.utils.datastructures.SortedDict`` wherever you were using ``django.newforms.forms.SortedDictFromList``. 2. Since ``SortedDict``'s copy method doesn't return a deepcopy as ``SortedDictFromList'``s copy method did, you will need to update your code if you were relying on ``SortedDictFromList.copy`` to return a deepcopy. Do this by using ``copy.deepcopy`` instead of ``SortedDict``'s copy method. * Change to ``APPEND_SLASH`` behaviour. In 0.96, if a URL didn't end in a slash or have a period in the final component of it's path, and ``APPEND_SLASH`` was True, Django would redirect to the same URL, but with a slash appended to the end. Now, Django checks to see if the pattern without the trailing slash would be matched by something in your URL patterns. If so, no redirection takes place, because it is assumed you deliberately wanted to catch that pattern. For most people, this won't require any changes. Some people, though, have URL patterns that look like this:: r'/some_prefix/(.*)$' Previously, those patterns would have been redirected to have a trailing slash. If you always want a slash on such URLs, rewrite the pattern as:: r'/some_prefix/(.*/)$' * Introduced ``DecimalField`` and changed ``FloatField`` to proper float - one that takes no ``max_digits``:: # 0.96 class MyModel(models.Model): ... field_name = models.FloatField(max_digits=10, decimal_places=3) #1.0 class MyModel(models.Model): ... field_name = models.DecimalField(max_digits=10, decimal_places=3) If you forget to make this change, you will see errors about ``FloatField`` not taking a ``max_digits`` attribute in ``__init__``, since the new ``FloatField`` takes no precision-related arguments. If you are using MySQL or PostgreSQL, there are no further changes needed. The database column types for ``DecimalField`` are the same as for the old ``FloatField``. If you are using SQLite, you need to force the database to view the appropriate columns as decimal types, rather than floats. To do this, follow this procedure for every application you have that contains a ``DecimalField``. Do this after you have made the change to using ``DecimalField`` in your code and updated the Django code. Warning: Back up your database first! For SQLite, this means making a copy of the single file that stores the database (the name of that file is the ``DATABASE_NAME`` in your settings.py file). For every application using a ``DecimalField``, do the following. We will use applications called some_app and another_app in this example:: ./manage.py dumpdata --format=xml some_app another_app > data-dump.xml ./manage.py reset some_app another_app ./manage.py loaddata data-dump.xml Notes: 1. It is important that you remember to use XML format in the first step of this process. We are exploiting a feature of the XML data dumps that makes porting floats to decimals with SQLite possible. 2. In the second step you will be asked to confirm that you are prepared to lose the data for the application(s) in question. We restore this data in the third step, of course. 3. DecimalField is not used in any of the apps shipped with Django prior to this change being made, so you do not need to worry about performing this procedure for any of the standard Django applications. If something goes wrong in the above process, just copy your backed up database file over the top of the original file and start again. * Almost *all* of the database backend-level functions have been renamed and/or relocated. None of these were documented, but you'll need to change your code if you're using any of these functions: ============================================= ========================================================= 0.96 name/location 1.0 name/location ============================================= ========================================================= django.db.backend.get_autoinc_sql django.db.connection.ops.autoinc_sql django.db.backend.get_date_extract_sql django.db.connection.ops.date_extract_sql django.db.backend.get_date_trunc_sql django.db.connection.ops.date_trunc_sql django.db.backend.get_datetime_cast_sql django.db.connection.ops.datetime_cast_sql django.db.backend.get_deferrable_sql django.db.connection.ops.deferrable_sql django.db.backend.get_drop_foreignkey_sql django.db.connection.ops.drop_foreignkey_sql django.db.backend.get_fulltext_search_sql django.db.connection.ops.fulltext_search_sql django.db.backend.get_last_insert_id django.db.connection.ops.last_insert_id django.db.backend.get_limit_offset_sql django.db.connection.ops.limit_offset_sql django.db.backend.get_max_name_length django.db.connection.ops.max_name_length django.db.backend.get_pk_default_value django.db.connection.ops.pk_default_value django.db.backend.get_random_function_sql django.db.connection.ops.random_function_sql django.db.backend.get_sql_flush django.db.connection.ops.sql_flush django.db.backend.get_sql_sequence_reset django.db.connection.ops.sequence_reset_sql django.db.backend.get_start_transaction_sql django.db.connection.ops.start_transaction_sql django.db.backend.get_tablespace_sql django.db.connection.ops.tablespace_sql django.db.backend.quote_name django.db.connection.ops.quote_name django.db.backend.get_query_set_class django.db.connection.ops.query_set_class django.db.backend.get_field_cast_sql django.db.connection.ops.field_cast_sql django.db.backend.get_drop_sequence django.db.connection.ops.drop_sequence_sql django.db.backend.OPERATOR_MAPPING django.db.connection.operators django.db.backend.allows_group_by_ordinal django.db.connection.features.allows_group_by_ordinal django.db.backend.allows_unique_and_pk django.db.connection.features.allows_unique_and_pk django.db.backend.autoindexes_primary_keys django.db.connection.features.autoindexes_primary_keys django.db.backend.needs_datetime_string_cast django.db.connection.features.needs_datetime_string_cast django.db.backend.needs_upper_for_iops django.db.connection.features.needs_upper_for_iops django.db.backend.supports_constraints django.db.connection.features.supports_constraints django.db.backend.supports_tablespaces django.db.connection.features.supports_tablespaces django.db.backend.uses_case_insensitive_names django.db.connection.features.uses_case_insensitive_names django.db.backend.uses_custom_queryset django.db.connection.features.uses_custom_queryset ============================================= =========================================================