Commits

Alessandro Pagnin committed f13f3dd Draft

Imported from svn by Bitbucket

Comments (0)

Files changed (9)

+transmeta was created at Yaco Systems, originally for Turismo Andaluz.
+
+Transmeta authors are:
+
+  * Marc Garcia <garcia.marc@gmail.com>
+  * Manuel Saelices <msaelices@yaco.es>
+  * Pablo Martin <goinnn@gmail.com>
+0.6.8 (2012-06-22)
+------------------
+
+- Fix a little bug in the command sync_transmeta_db (UnboundLocalError: local variable 'f' referenced before assignment)
+
+0.6.7 (2012-03-20)
+------------------
+
+- Change the representation (verbose_name) of the transmeta labels 
+
+
+0.6.6 (2012-02-06)
+------------------
+
+- Improvements and usability in the command sync_transmeta_db
+- Fix some bugs
+- Documentation
+
+
+0.6.5 (2012-01-13)
+------------------
+
+- Improvements and usability in the command sync_transmeta_db
+- Works with the last django (the command sync_transmeta_db)
+- Works with mysql (the command sync_transmeta_db)
+
+
+0.6.4 (2011-11-29)
+------------------
+
+- Fixes error with inheritance in models.
+
+0.6.3 (2011-11-29)
+------------------
+
+- Allow to use a TRANSMETA_LANGUAGES settings.
+- Added two options to sync_transmeta_db: -y (assume yes on all) and -d (default language code)
+
+
+0.6.2 (2011-03-22)
+------------------
+
+- works when default locale have spelling variants as es-ES or en-US.
+
+
+0.6.1 (2011-03-17)
+------------------
+
+- get_all_translatable_fields does not returned the correct tuple. Problems with inheritance.
+
+0.6.0 (2011-02-24)
+------------------
+
+- Make compatible with Django 1.2 and 1.3 when using ugettext_lazy in models verbose_name, fixing a hidden bug also for Django 1.1
+
+           GNU LESSER GENERAL PUBLIC LICENSE
+                       Version 3, 29 June 2007
+
+ Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+
+  This version of the GNU Lesser General Public License incorporates
+the terms and conditions of version 3 of the GNU General Public
+License, supplemented by the additional permissions listed below.
+
+  0. Additional Definitions.
+
+  As used herein, "this License" refers to version 3 of the GNU Lesser
+General Public License, and the "GNU GPL" refers to version 3 of the GNU
+General Public License.
+
+  "The Library" refers to a covered work governed by this License,
+other than an Application or a Combined Work as defined below.
+
+  An "Application" is any work that makes use of an interface provided
+by the Library, but which is not otherwise based on the Library.
+Defining a subclass of a class defined by the Library is deemed a mode
+of using an interface provided by the Library.
+
+  A "Combined Work" is a work produced by combining or linking an
+Application with the Library.  The particular version of the Library
+with which the Combined Work was made is also called the "Linked
+Version".
+
+  The "Minimal Corresponding Source" for a Combined Work means the
+Corresponding Source for the Combined Work, excluding any source code
+for portions of the Combined Work that, considered in isolation, are
+based on the Application, and not on the Linked Version.
+
+  The "Corresponding Application Code" for a Combined Work means the
+object code and/or source code for the Application, including any data
+and utility programs needed for reproducing the Combined Work from the
+Application, but excluding the System Libraries of the Combined Work.
+
+  1. Exception to Section 3 of the GNU GPL.
+
+  You may convey a covered work under sections 3 and 4 of this License
+without being bound by section 3 of the GNU GPL.
+
+  2. Conveying Modified Versions.
+
+  If you modify a copy of the Library, and, in your modifications, a
+facility refers to a function or data to be supplied by an Application
+that uses the facility (other than as an argument passed when the
+facility is invoked), then you may convey a copy of the modified
+version:
+
+   a) under this License, provided that you make a good faith effort to
+   ensure that, in the event an Application does not supply the
+   function or data, the facility still operates, and performs
+   whatever part of its purpose remains meaningful, or
+
+   b) under the GNU GPL, with none of the additional permissions of
+   this License applicable to that copy.
+
+  3. Object Code Incorporating Material from Library Header Files.
+
+  The object code form of an Application may incorporate material from
+a header file that is part of the Library.  You may convey such object
+code under terms of your choice, provided that, if the incorporated
+material is not limited to numerical parameters, data structure
+layouts and accessors, or small macros, inline functions and templates
+(ten or fewer lines in length), you do both of the following:
+
+   a) Give prominent notice with each copy of the object code that the
+   Library is used in it and that the Library and its use are
+   covered by this License.
+
+   b) Accompany the object code with a copy of the GNU GPL and this license
+   document.
+
+  4. Combined Works.
+
+  You may convey a Combined Work under terms of your choice that,
+taken together, effectively do not restrict modification of the
+portions of the Library contained in the Combined Work and reverse
+engineering for debugging such modifications, if you also do each of
+the following:
+
+   a) Give prominent notice with each copy of the Combined Work that
+   the Library is used in it and that the Library and its use are
+   covered by this License.
+
+   b) Accompany the Combined Work with a copy of the GNU GPL and this license
+   document.
+
+   c) For a Combined Work that displays copyright notices during
+   execution, include the copyright notice for the Library among
+   these notices, as well as a reference directing the user to the
+   copies of the GNU GPL and this license document.
+
+   d) Do one of the following:
+
+       0) Convey the Minimal Corresponding Source under the terms of this
+       License, and the Corresponding Application Code in a form
+       suitable for, and under terms that permit, the user to
+       recombine or relink the Application with a modified version of
+       the Linked Version to produce a modified Combined Work, in the
+       manner specified by section 6 of the GNU GPL for conveying
+       Corresponding Source.
+
+       1) Use a suitable shared library mechanism for linking with the
+       Library.  A suitable mechanism is one that (a) uses at run time
+       a copy of the Library already present on the user's computer
+       system, and (b) will operate properly with a modified version
+       of the Library that is interface-compatible with the Linked
+       Version.
+
+   e) Provide Installation Information, but only if you would otherwise
+   be required to provide such information under section 6 of the
+   GNU GPL, and only to the extent that such information is
+   necessary to install and execute a modified version of the
+   Combined Work produced by recombining or relinking the
+   Application with a modified version of the Linked Version. (If
+   you use option 4d0, the Installation Information must accompany
+   the Minimal Corresponding Source and Corresponding Application
+   Code. If you use option 4d1, you must provide the Installation
+   Information in the manner specified by section 6 of the GNU GPL
+   for conveying Corresponding Source.)
+
+  5. Combined Libraries.
+
+  You may place library facilities that are a work based on the
+Library side by side in a single library together with other library
+facilities that are not Applications and are not covered by this
+License, and convey such a combined library under terms of your
+choice, if you do both of the following:
+
+   a) Accompany the combined library with a copy of the same work based
+   on the Library, uncombined with any other library facilities,
+   conveyed under the terms of this License.
+
+   b) Give prominent notice with the combined library that part of it
+   is a work based on the Library, and explaining where to find the
+   accompanying uncombined form of the same work.
+
+  6. Revised Versions of the GNU Lesser General Public License.
+
+  The Free Software Foundation may publish revised and/or new versions
+of the GNU Lesser General Public License from time to time. Such new
+versions will be similar in spirit to the present version, but may
+differ in detail to address new problems or concerns.
+
+  Each version is given a distinguishing version number. If the
+Library as you received it specifies that a certain numbered version
+of the GNU Lesser General Public License "or any later version"
+applies to it, you have the option of following the terms and
+conditions either of that published version or of any later version
+published by the Free Software Foundation. If the Library as you
+received it does not specify a version number of the GNU Lesser
+General Public License, you may choose any version of the GNU Lesser
+General Public License ever published by the Free Software Foundation.
+
+  If the Library as you received it specifies that a proxy can decide
+whether future versions of the GNU Lesser General Public License shall
+apply, that proxy's public statement of acceptance of any version is
+permanent authorization for you to choose that version for the
+Library.
+Introduction
+============
+
+Transmeta is an application for translatable content in Django's models. Each
+language is stored and managed automatically in a different column at database
+level.
+
+Features
+========
+
+* Automatic schema creation with translatable fields. 
+* Translatable fields integrated into Django's admin interface.
+* Command to synchronize database schema to add new translatable fields and new languages.
+
+Using transmeta
+===============
+
+Creating translatable models
+----------------------------
+
+Look at this model::
+
+    class Book(models.Model):
+        title = models.CharField(max_length=200)
+        description = models.TextField()
+        body = models.TextField(default='')
+        price = models.FloatField()
+
+Suppose you want to make ``description`` and ``body`` translatable. The resulting model after using ``transmeta`` is::
+
+
+    from transmeta import TransMeta
+
+    class Book(models.Model):
+        __metaclass__ = TransMeta
+
+        title = models.CharField(max_length=200)
+        description = models.TextField()
+        body = models.TextField(default='')
+        price = models.FloatField()
+
+        class Meta:
+            translate = ('description', 'body', )
+
+Make sure you have set the default and available languages in your ``settings.py``::
+
+    LANGUAGE_CODE = 'es'
+
+    ugettext = lambda s: s # dummy ugettext function, as django's docs say
+
+    LANGUAGES = (
+        ('es', ugettext('Spanish')),
+        ('en', ugettext('English')),
+    )
+
+Notes:
+
+* It's possible that you want have a default language in your site, but this is not the default language to transmeta. You can set this variable in your settings::
+
+    TRANSMETA_DEFAULT_LANGUAGE = 'it'
+
+* The same it's possible with the languages::
+
+    TRANSMETA_LANGUAGES = (
+        ('es', ugettext('Spanish')),
+        ('en', ugettext('English')),
+        ('en', ugettext('Italian')),
+    )
+
+This is the SQL generated with the ``./manage.py sqlall`` command::
+
+    BEGIN;
+    CREATE TABLE "fooapp_book" (
+        "id" serial NOT NULL PRIMARY KEY,
+        "title" varchar(200) NOT NULL,
+        "description_en" text,
+        "description_es" text NOT NULL,
+        "body_es" text NOT NULL,
+        "body_en" text NOT NULL,
+        "price" double precision NOT NULL
+    )
+    ;
+    COMMIT;
+
+Notes:
+
+* ``transmeta`` creates one column for each language. Don't worry about needing new languages in the future, ``transmeta`` solves this problem for you.
+* If one field is ``null=False`` and doesn't have a default value, ``transmeta`` will create only one ``NOT NULL`` field, for the default language. Fields for other secondary languages will be nullable. Also, the primary language will be required in the admin app, while the other fields will be optional (with ``blank=True``). This was done so because the normal approach for content translation is first add content in the main language and later have translators translate into other languages.
+* You can use ``./manage.py syncdb`` to create database schema.
+
+Playing in the python shell
+---------------------------
+
+``transmeta`` creates one field for every available language for every translatable field defined in a model. Field names are suffixed with language short codes, e.g.: ``description_es``, ``description_en``, and so on. In addition it creates a ``field_name`` getter to retrieve the field value in the active language.
+
+Let's play a bit in a python shell to best understand how this works::
+
+    >>> from fooapp.models import Book
+    >>> b = Book.objects.create(description_es=u'mi descripcion', description_en=u'my description')
+    >>> b.description
+    u'my description'
+    >>> from django.utils.translation import activate
+    >>> activate('es')
+    >>> b.description
+    u'mi descripcion'
+    >>> b.description_en
+    u'my description'
+
+Adding new languages
+--------------------
+
+If you need to add new languages to the existing ones you only need to change your settings.py and ask transmeta to sync the DB again. For example, to add French to our project, you need to add it to LANGUAGES in ``settings.py``::
+
+    LANGUAGES = (
+        ('es', ugettext('Spanish')),
+        ('en', ugettext('English')),
+        ('fr', ugettext('French')),
+    )
+
+And execute a special ``sync_transmeta_db`` command::
+
+    $ ./manage.py sync_transmeta_db
+
+    This languages can change in "description" field from "fooapp.book" model: fr
+
+    SQL to synchronize "fooapp.book" schema:
+       ALTER TABLE "fooapp_book" ADD COLUMN "description_fr" text
+
+    Are you sure that you want to execute the previous SQL: (y/n) [n]: y
+    Executing SQL... Done
+
+    This languages can change in "body" field from "fooapp.book" model: fr
+
+    SQL to synchronize "fooapp.book" schema:
+       ALTER TABLE "fooapp_book" ADD COLUMN "body_fr" text
+
+    Are you sure that you want to execute the previous SQL: (y/n) [n]: y
+    Executing SQL... Done
+
+And done!
+
+Adding new translatable fields
+------------------------------
+
+Now imagine that, after several months using this web app (with many books created), you need to make book price translatable (for example because book price depends on currency).
+
+To achieve this, first add ``price`` to the model's translatable fields list::
+
+    class Book(models.Model):
+        ...
+        price = models.FloatField()
+
+        class Meta:
+            translate = ('description', 'body', 'price', )
+
+All that's left now is calling the ``sync_transmeta_db`` command to update the DB schema::
+
+    $ ./manage.py sync_transmeta_db
+
+    This languages can change in "price" field from "fooapp.book" model: es, en
+
+    SQL to synchronize "fooapp.book" schema:
+        ALTER TABLE "fooapp_book" ADD COLUMN "price_es" double precision
+        UPDATE "fooapp_book" SET "price_es" = "price"
+        ALTER TABLE "fooapp_book" ALTER COLUMN "price_es" SET NOT NULL
+        ALTER TABLE "fooapp_book" ADD COLUMN "price_en" double precision
+        ALTER TABLE "fooapp_book" DROP COLUMN "price"
+
+    Are you sure that you want to execute the previous SQL: (y/n) [n]: y
+    Executing SQL...Done
+
+What the hell this command does?
+
+``sync_transmeta_db`` command not only creates new database columns for new translatable field... it copy data from old ``price`` field into one of languages, and that is why command ask you for destination language field for actual data. It's very important that the LANGUAGE_CODE and LANGUAGES (or TRANSMETA_DEFAULT_LANGUAGE, TRANSMETA_LANGUAGES) settings have good values.  
+
+This command also you can execute, when you want add a language to the site, or you want to change the default language in ``transmeta``. For this last case, you can define a variable in the settings file::
+
+    TRANSMETA_VALUE_DEFAULT = '---'
+
+
+Admin integration
+-----------------
+
+``transmeta`` transparently displays all translatable fields into the admin interface. This is easy because models have in fact many fields (one for each language).
+
+Changing form fields in the admin is quite a common task, and ``transmeta`` includes the ``canonical_fieldname`` utility function to apply these changes for all language fields at once. It's better explained with an example::
+
+    from transmeta import canonical_fieldname
+
+    class BookAdmin(admin.ModelAdmin):
+        def formfield_for_dbfield(self, db_field, **kwargs):
+            field = super(BookAdmin, self).formfield_for_dbfield(db_field, **kwargs)
+            db_fieldname = canonical_fieldname(db_field)
+            if db_fieldname == 'description':
+                # this applies to all description_* fields
+                field.widget = MyCustomWidget()
+            elif field.name == 'body_es':
+                # this applies only to body_es field
+                field.widget = MyCustomWidget()
+            return field
+# Copyright (c) 2010 by Yaco Sistemas <pmartin@yaco.es>
+#
+# This software is free software: you can redistribute it and/or modify
+# it under the terms of the GNU Lesser General Public License as published by
+# the Free Software Foundation, either version 3 of the License, or
+# (at your option) any later version.
+#
+# This software is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+# GNU Lesser General Public License for more details.
+#
+# You should have received a copy of the GNU Lesser General Public License
+# along with this software.  If not, see <http://www.gnu.org/licenses/>.
+
+import os
+from setuptools import setup, find_packages
+
+
+def read(*rnames):
+    return open(os.path.join(os.path.dirname(__file__), *rnames)).read()
+
+long_description = (
+    read('README')
+    + '\n' +
+    'Authors\n'
+    '************\n'
+    + '\n' +
+    read('AUTHORS')
+    + '\n' +
+    'Change history\n'
+    '**************\n'
+    + '\n' +
+    read('CHANGES')
+    + '\n' +
+   'Download\n'
+    '********\n')
+
+setup(
+    name="django-transmeta",
+    version="0.6.8",
+    author="Yaco Sistemas S.L.",
+    author_email="garcia.marc@gmail.com",
+    description="Transmeta is an application for translatable content in Django's models.",
+    long_description=long_description,
+    classifiers=[
+        'Development Status :: 4 - Beta',
+        'Framework :: Django',
+        'License :: OSI Approved :: GNU Library or Lesser General Public License (LGPL)',
+    ],
+    license="LGPL 3",
+    keywords="django,translation,internationalization,i18n,transmeta,models,translation models",
+    url='http://code.google.com/p/django-transmeta/',
+    packages=find_packages('.'),
+    package_dir= {'': '.'},
+    zip_safe=False,
+)

transmeta/__init__.py

+import copy
+
+from django.db import models
+from django.db.models.fields import NOT_PROVIDED
+from django.conf import settings
+from django.core.exceptions import ImproperlyConfigured
+from django.utils.datastructures import SortedDict
+from django.utils.translation import get_language, ugettext_lazy as _
+
+
+LANGUAGE_CODE = 0
+LANGUAGE_NAME = 1
+
+
+def get_languages():
+    return getattr(settings, 'TRANSMETA_LANGUAGES', settings.LANGUAGES)
+
+
+def get_real_fieldname(field, lang=None):
+    if lang is None:
+        lang = get_language().split('-')[0]  # both 'en-US' and 'en' -> 'en'
+    return str('%s_%s' % (field, lang))
+
+
+def get_field_language(real_field):
+    """ return language for a field. i.e. returns "en" for "name_en" """
+    return real_field.split('_')[1]
+
+
+def get_fallback_fieldname(field, lang=None):
+    return get_real_fieldname(field, lang=fallback_language())
+
+
+def get_real_fieldname_in_each_language(field):
+    return [get_real_fieldname(field, lang[LANGUAGE_CODE])
+            for lang in get_languages()]
+
+
+def canonical_fieldname(db_field):
+    """ all "description_en", "description_fr", etc. field names will return "description" """
+    return getattr(db_field, 'original_fieldname', db_field.name)  # original_fieldname is set by transmeta
+
+
+def fallback_language():
+    """ returns fallback language """
+    return getattr(settings, 'TRANSMETA_DEFAULT_LANGUAGE', \
+                   settings.LANGUAGE_CODE)
+
+
+def get_all_translatable_fields(model, model_trans_fields=None, column_in_current_table=False):
+    """ returns all translatable fields in a model (including superclasses ones) """
+    if model_trans_fields is None:
+        model_trans_fields = set()
+    model_trans_fields.update(set(getattr(model._meta, 'translatable_fields', [])))
+    for parent in model.__bases__:
+        if getattr(parent, '_meta', None) and (not column_in_current_table or parent._meta.abstract):
+            get_all_translatable_fields(parent, model_trans_fields, column_in_current_table)
+    return tuple(model_trans_fields)
+
+
+def default_value(field):
+    '''
+    When accessing to the name of the field itself, the value
+    in the current language will be returned. Unless it's set,
+    the value in the default language will be returned.
+    '''
+
+    def default_value_func(self):
+        attname = lambda x: get_real_fieldname(field, x)
+
+        if getattr(self, attname(get_language()), None):
+            result = getattr(self, attname(get_language()))
+        elif getattr(self, attname(get_language()[:2]), None):
+            result = getattr(self, attname(get_language()[:2]))
+        else:
+            default_language = fallback_language()
+            result = getattr(self, attname(default_language), None)
+        return result
+
+    return default_value_func
+
+
+class TransMeta(models.base.ModelBase):
+    '''
+    Metaclass that allow a django field, to store a value for
+    every language. The syntax to us it is next:
+
+        class MyClass(models.Model):
+            __metaclass__ = transmeta.TransMeta
+
+            my_field = models.CharField(max_length=20)
+            my_i18n_field = models.CharField(max_length=30)
+
+            class Meta:
+                translate = ('my_i18n_field',)
+
+    Then we'll be able to access a specific language by
+    <field_name>_<language_code>. If just <field_name> is
+    accessed, we'll get the value of the current language,
+    or if null, the value in the default language.
+    '''
+
+    def __new__(cls, name, bases, attrs):
+        attrs = SortedDict(attrs)
+        if 'Meta' in attrs and hasattr(attrs['Meta'], 'translate'):
+            fields = attrs['Meta'].translate
+            delattr(attrs['Meta'], 'translate')
+        else:
+            new_class = super(TransMeta, cls).__new__(cls, name, bases, attrs)
+            # we inherits possible translatable_fields from superclasses
+            abstract_model_bases = [base for base in bases if hasattr(base, '_meta') \
+                                    and base._meta.abstract]
+            translatable_fields = []
+            for base in abstract_model_bases:
+                if hasattr(base._meta, 'translatable_fields'):
+                    translatable_fields.extend(list(base._meta.translatable_fields))
+            new_class._meta.translatable_fields = tuple(translatable_fields)
+            return new_class
+
+        if not isinstance(fields, tuple):
+            raise ImproperlyConfigured("Meta's translate attribute must be a tuple")
+
+        default_language = fallback_language()
+
+        for field in fields:
+            if not field in attrs or \
+               not isinstance(attrs[field], models.fields.Field):
+                    raise ImproperlyConfigured(
+                        "There is no field %(field)s in model %(name)s, "\
+                        "as specified in Meta's translate attribute" % \
+                        dict(field=field, name=name))
+            original_attr = attrs[field]
+            for lang in get_languages():
+                lang_code = lang[LANGUAGE_CODE]
+                lang_name = lang[LANGUAGE_NAME]
+                lang_attr = copy.copy(original_attr)
+                lang_attr.original_fieldname = field
+                lang_attr_name = get_real_fieldname(field, lang_code)
+                if lang_code != default_language:
+                    # only will be required for default language
+                    if not lang_attr.null and lang_attr.default is NOT_PROVIDED:
+                        lang_attr.null = True
+                    if not lang_attr.blank:
+                        lang_attr.blank = True
+                if hasattr(lang_attr, 'verbose_name'):
+                    lang_attr.verbose_name = LazyString(lang_attr.verbose_name, _(lang_name))
+                attrs[lang_attr_name] = lang_attr
+            del attrs[field]
+            attrs[field] = property(default_value(field))
+
+        new_class = super(TransMeta, cls).__new__(cls, name, bases, attrs)
+        if hasattr(new_class, '_meta'):
+            new_class._meta.translatable_fields = fields
+        return new_class
+
+
+class LazyString(object):
+
+    def __init__(self, proxy, lang):
+        self.proxy = proxy
+        self.lang = lang
+
+    def __unicode__(self):
+        return u'%s (%s)' % (self.proxy, self.lang)

transmeta/management/__init__.py

Empty file added.

transmeta/management/commands/__init__.py

Empty file added.

transmeta/management/commands/sync_transmeta_db.py

+"""
+ Detect new translatable fields in all models and sync database structure.
+
+ You will need to execute this command in two cases:
+
+   1. When you add new languages to settings.LANGUAGES.
+   2. When you new translatable fields to your models.
+
+"""
+import re
+
+from optparse import make_option
+
+from django.conf import settings
+from django.core.management.base import BaseCommand
+from django.core.management.color import no_style
+from django.db import connection, transaction
+from django.db import backend
+from django.db.models import get_models
+from django.db.models.fields import FieldDoesNotExist
+
+from transmeta import (fallback_language, get_real_fieldname,
+                       get_languages, get_all_translatable_fields)
+
+VALUE_DEFAULT = 'WITHOUT VALUE'
+
+
+def ask_for_confirmation(sql_sentences, model_full_name, assume_yes):
+    print '\nSQL to synchronize "%s" schema:' % model_full_name
+    for sentence in sql_sentences:
+        print '   %s' % sentence
+    if assume_yes:
+        print '\nAre you sure that you want to execute the previous SQL: (y/n) [n]: YES'
+        return True
+    while True:
+        prompt = '\nAre you sure that you want to execute the previous SQL: (y/n) [n]: '
+        answer = raw_input(prompt).strip()
+        if answer == '':
+            return False
+        elif answer not in ('y', 'n', 'yes', 'no'):
+            print 'Please answer yes or no'
+        elif answer == 'y' or answer == 'yes':
+            return True
+        else:
+            return False
+
+
+def print_db_change_langs(db_change_langs, field_name, model_name):
+    print '\nThis languages can change in "%s" field from "%s" model: %s' % \
+        (field_name, model_name, ", ".join(db_change_langs))
+
+
+class Command(BaseCommand):
+    help = "Detect new translatable fields or new available languages and sync database structure"
+
+    option_list = BaseCommand.option_list + (
+        make_option('-y', '--yes', action='store_true', dest='assume_yes',
+                    help="Assume YES on all queries"),
+        make_option('-d', '--default', dest='default_language',
+                    help="Language code of your default language"),
+        )
+
+    def handle(self, *args, **options):
+        """ command execution """
+        assume_yes = options.get('assume_yes', False)
+        default_language = options.get('default_language', None)
+
+        # set manual transaction management
+        transaction.commit_unless_managed()
+        transaction.enter_transaction_management()
+        transaction.managed(True)
+
+        self.cursor = connection.cursor()
+        self.introspection = connection.introspection
+
+        self.default_lang = default_language or fallback_language()
+
+        all_models = get_models()
+        found_db_change_fields = False
+        for model in all_models:
+            if hasattr(model._meta, 'translatable_fields'):
+                model_full_name = '%s.%s' % (model._meta.app_label, model._meta.module_name)
+                translatable_fields = get_all_translatable_fields(model, column_in_current_table=True)
+                db_table = model._meta.db_table
+                for field_name in translatable_fields:
+                    db_table_fields = self.get_table_fields(db_table)
+                    db_change_langs = list(set(list(self.get_db_change_languages(field_name, db_table_fields)) + [self.default_lang]))
+                    if db_change_langs:
+                        sql_sentences = self.get_sync_sql(field_name, db_change_langs, model, db_table_fields)
+                        if sql_sentences:
+                            found_db_change_fields = True
+                            print_db_change_langs(db_change_langs, field_name, model_full_name)
+                            execute_sql = ask_for_confirmation(sql_sentences, model_full_name, assume_yes)
+                            if execute_sql:
+                                print 'Executing SQL...',
+                                for sentence in sql_sentences:
+                                    self.cursor.execute(sentence)
+                                    # commit
+                                    transaction.commit()
+                                print 'Done'
+                            else:
+                                print 'SQL not executed'
+
+        if transaction.is_dirty():
+            transaction.commit()
+        transaction.leave_transaction_management()
+
+        if not found_db_change_fields:
+            print '\nNo new translatable fields detected'
+        if default_language:
+            variable = 'TRANSMETA_DEFAULT_LANGUAGE'
+            has_transmeta_default_language = getattr(settings, variable, False)
+            if not has_transmeta_default_language:
+                variable = 'LANGUAGE_CODE'
+            if getattr(settings, variable) != default_language:
+                print ('\n\nYou should change in your settings '
+                       'the %s variable to "%s"' % (variable, default_language))
+
+    def get_table_fields(self, db_table):
+        """ get table fields from schema """
+        db_table_desc = self.introspection.get_table_description(self.cursor, db_table)
+        return [t[0] for t in db_table_desc]
+
+    def get_field_required_in_db(self, db_table, field_name, value_not_implemented=False):
+        table_fields = self.introspection.get_table_description(self.cursor, db_table)
+        for f in table_fields:
+            if f[0] == field_name:
+                is_null = f[-1]
+                if is_null is None:  # Not Implemented
+                    return value_not_implemented
+                return not is_null
+        return False
+
+    def get_db_change_languages(self, field_name, db_table_fields):
+        """ get only db changes fields """
+        for lang_code, lang_name in get_languages():
+            if get_real_fieldname(field_name, lang_code) not in db_table_fields:
+                yield lang_code
+        for db_table_field in db_table_fields:
+            pattern = re.compile('^%s_(?P<lang>\w{2})$' % field_name)
+            m = pattern.match(db_table_field)
+            if not m:
+                continue
+            lang = m.group('lang')
+            yield lang
+
+    def was_translatable_before(self, field_name, db_table_fields):
+        """ check if field_name was translatable before syncing schema """
+        if field_name in db_table_fields:
+            # this implies field was never translatable before, data is in this field
+            return False
+        else:
+            return True
+
+    def get_default_field(self, field_name, model):
+        for lang_code, lang_name in get_languages():
+            field_name_i18n = get_real_fieldname(field_name, lang_code)
+            f = model._meta.get_field(field_name_i18n)
+            if not f.null:
+                return f
+        try:
+            return model._meta.get_field(field_name)
+        except FieldDoesNotExist:
+            return None
+
+    def get_value_default(self):
+        return getattr(settings, 'TRANSMETA_VALUE_DEFAULT', VALUE_DEFAULT)
+
+    def get_type_of_db_field(self, field_name, model):
+        field = self.get_default_field(field_name, model)
+        if not field:
+            field = model._meta.get_field(get_real_fieldname(field_name))
+        try:
+            col_type = field.db_type(connection)
+        except TypeError:  # old django
+            col_type = field.db_type()
+        return col_type
+
+    def get_sync_sql(self, field_name, db_change_langs, model, db_table_fields):
+        """ returns SQL needed for sync schema for a new translatable field """
+        qn = connection.ops.quote_name
+        style = no_style()
+        sql_output = []
+        db_table = model._meta.db_table
+        was_translatable_before = self.was_translatable_before(field_name, db_table_fields)
+        default_f = self.get_default_field(field_name, model)
+        default_f_required = default_f and self.get_field_required_in_db(db_table,
+                                                    default_f.name,
+                                                    value_not_implemented=False)
+        for lang in db_change_langs:
+            new_field = get_real_fieldname(field_name, lang)
+            try:
+                f = model._meta.get_field(new_field)
+                col_type = self.get_type_of_db_field(field_name, model)
+                field_column = f.column
+            except FieldDoesNotExist:  # columns in db, removed the settings.LANGUGES
+                field_column = new_field
+                col_type = self.get_type_of_db_field(field_name, model)
+            field_sql = [style.SQL_FIELD(qn(field_column)), style.SQL_COLTYPE(col_type)]
+
+            alter_colum_set = 'ALTER COLUMN %s SET' % qn(field_column)
+            if default_f:
+                alter_colum_drop = 'ALTER COLUMN %s DROP' % qn(field_column)
+            not_null = style.SQL_KEYWORD('NOT NULL')
+
+            if 'mysql' in backend.__name__:
+                alter_colum_set = 'MODIFY %s %s' % (qn(field_column), col_type)
+                not_null = style.SQL_KEYWORD('NULL')
+                if default_f:
+                    alter_colum_drop = 'MODIFY %s %s' % (qn(field_column), col_type)
+
+            # column creation
+            if not new_field in db_table_fields:
+                sql_output.append("ALTER TABLE %s ADD COLUMN %s" % (qn(db_table), ' '.join(field_sql)))
+
+            if lang == self.default_lang and not was_translatable_before:
+                # data copy from old field (only for default language)
+                sql_output.append("UPDATE %s SET %s = %s" % (qn(db_table), \
+                                    qn(field_column), qn(field_name)))
+                if not f.null:
+                    # changing to NOT NULL after having data copied
+                    sql_output.append("ALTER TABLE %s %s %s" % \
+                                    (qn(db_table), alter_colum_set, \
+                                    style.SQL_KEYWORD('NOT NULL')))
+            elif default_f and not default_f.null:
+                if lang == self.default_lang:
+                    f_required = self.get_field_required_in_db(db_table,
+                                                           field_column,
+                                                           value_not_implemented=False)
+                    if default_f.name == new_field and default_f_required:
+                        continue
+                    if not f_required:
+                        # data copy from old field (only for default language)
+                        sql_output.append(("UPDATE %(db_table)s SET %(f_colum)s = '%(value_default)s' "
+                                    "WHERE %(f_colum)s is %(null)s or %(f_colum)s = '' " %  
+                                        {'db_table': qn(db_table),
+                                        'f_colum': qn(field_column),
+                                        'value_default': self.get_value_default(),
+                                        'null': style.SQL_KEYWORD('NULL'),
+                                        }))
+                        # changing to NOT NULL after having data copied
+                        sql_output.append("ALTER TABLE %s %s %s" % \
+                                        (qn(db_table), alter_colum_set, \
+                                        style.SQL_KEYWORD('NOT NULL')))
+                else:
+                    f_required = self.get_field_required_in_db(db_table,
+                                                           field_column,
+                                                           value_not_implemented=True)
+                    if f_required:
+                        sql_output.append(("ALTER TABLE %s %s %s" % 
+                                        (qn(db_table), alter_colum_drop, not_null)))
+
+        if not was_translatable_before:
+            # we drop field only if field was no translatable before
+            sql_output.append("ALTER TABLE %s DROP COLUMN %s" % (qn(db_table), qn(field_name)))
+        return sql_output