예제 #1
0
def _load_conf(*args, **kwargs):
    """  Ensures the configuration module gets imported when importing model_i18n. """
    # This is an idea from haystack app. We need to run the code that
    # follows only once, no matter how many times the main module is imported.
    # We'll look through the stack to see if we appear anywhere and simply
    # return if we do, allowing the original call to finish.
    stack = inspect.stack()
    for stack_info in stack[1:]:
        if '_load_conf' in stack_info[3]:
            return

    if not hasattr(settings, 'MODEL_I18N_CONF'):
        raise ImproperlyConfigured('You must define the MODEL_I18N_CONF setting, it should be a python module path string, for example "myproject.i18n_conf"')
    if not hasattr(settings, 'MODEL_I18N_MASTER_LANGUAGE'):
        raise ImproperlyConfigured('You must define the MODEL_I18N_MASTER_LANGUAGE setting.')

    # Import config module
    import_module(settings.MODEL_I18N_CONF)
예제 #2
0
    def register(self, master_model, translation_class=None, **options):
        if type(master_model) is str:
            app_path = ".".join(master_model.split(".")[:-1])
            master_module_models = import_module(app_path + '.models')
            master_model = getattr(master_module_models, master_model.split(".")[-1])
            #print master_model
            #return
        if master_model in self._registry:
            raise AlreadyRegistered('The model "%s" has is already \
            registered for translation' % master_model.__name__)

        # If not translation_class given use default options.
        if not translation_class:
            translation_class = ModelTranslation

        # If we got **options then dynamically construct a
        # subclass of translation_class with those **options.
        if options:
            translation_class = type('%sTranslation' % \
            master_model.__name__, (translation_class,), options)

        # Validate the translation_class (just in debug mode).
        if settings.DEBUG:
            from model_i18n.validation import validate
            validate(translation_class, master_model)

        transmanager_class = type('%sTransManager' % master_model.__name__, (TransManager, master_model.objects.__class__,), {})
        livetransmanager_class = transmanager_class
        try:
            livetransmanager_class = type('%sLiveTransManager' % master_model.__name__, (TransManager, master_model.live_objects.__class__,), {})
        except:
            pass

        master_model.add_to_class('_default_manager', TransManager())
        master_model.add_to_class('_base_manager', TransManager())
        master_model.add_to_class('objects', transmanager_class())
        master_model.add_to_class('live_objects', livetransmanager_class())

        opts = translation_class(master_model)

        # Set up master_model as a multilingual model
        # using translation_class options
        tmodel = self.create_translation_model(master_model, opts)
        tmodel.__unicode__ = lambda s: unicode(getattr(s, s._transmeta.master_field_name))
        defaults = {'blank': True, 'null': True, 'editable': False}
        m2mfield = models.ManyToManyField(tmodel, **defaults)
        master_model.add_to_class("translations", m2mfield)

        # This probably will become a class method soon.
        self.setup_master_model(master_model, tmodel)
        if MODEL_I18N_DJANGO_ADMIN:
            self._registry_admin[master_model] = tmodel

        # Register the multilingual model and the used translation_class.
        self._registry[master_model] = opts
예제 #3
0
def autodiscover(module_name='translations'):
    """
    Auto-discover translations.py files in installed app's directories, fail
    silently if not present. This forces an import on them to register any
    translation bits they may want.

    Based on django's contrib.admin autodiscover().
    """
    import imp
    from model_i18n.utils import import_module
    from django.conf import settings


    for app in settings.INSTALLED_APPS:
        # For each app, we need to look for `module_name` in that app's
        # package. We can't use os.path here -- recall that modules may be
        # imported different ways (think zip files) -- so we need to get
        # the app's __path__ and look for translation.py on that path.

        # Step 1: find out the app's __path__ Import errors here will (and
        # should) bubble up, but a missing __path__ (which is legal, but weird)
        # fails silently. Try with dirname of module file if __path__ attribute
        # is not present.
        app_module = import_module(app)
        if hasattr(app_module, '__path__'):
            app_path = app_module.__path__
        else:
            app_path = dirname(app_module.__file__)

        # Step 2: use imp.find_module to find the app's `module_name`. For some
        # reason imp.find_module raises ImportError if the app can't be found
        # but doesn't actually try to import the module. So skip this app if
        # its `module_name` doesn't exist
        try:
            imp.find_module(module_name, app_path)
        except ImportError, e:
            continue

        # Step 3: import the app's translation file.
        # If this has errors we want them to bubble up.
        import_module('.'.join([app, module_name]))
예제 #4
0
def _load_conf(*args, **kwargs):
    """  Ensures the configuration module gets imported when importing model_i18n. """
    # This is an idea from haystack app. We need to run the code that
    # follows only once, no matter how many times the main module is imported.
    # We'll look through the stack to see if we appear anywhere and simply
    # return if we do, allowing the original call to finish.
    stack = inspect.stack()
    for stack_info in stack[1:]:
        if '_load_conf' in stack_info[3]:
            return

    if not hasattr(settings, 'MODEL_I18N_CONF'):
        raise ImproperlyConfigured(
            'You must define the MODEL_I18N_CONF setting, it should be a python module path string, for example "myproject.i18n_conf"'
        )
    if not hasattr(settings, 'MODEL_I18N_MASTER_LANGUAGE'):
        raise ImproperlyConfigured(
            'You must define the MODEL_I18N_MASTER_LANGUAGE setting.')

    # Import config module
    import_module(settings.MODEL_I18N_CONF)
예제 #5
0
def autodiscover(module_name='translations'):
    """
    Auto-discover translations.py files in installed app's directories, fail
    silently if not present. This forces an import on them to register any
    translation bits they may want.

    Based on django's contrib.admin autodiscover().
    """
    import imp
    from django.conf import settings

    for app in settings.INSTALLED_APPS:
        # For each app, we need to look for `module_name` in that app's
        # package. We can't use os.path here -- recall that modules may be
        # imported different ways (think zip files) -- so we need to get
        # the app's __path__ and look for translation.py on that path.

        # Step 1: find out the app's __path__ Import errors here will (and
        # should) bubble up, but a missing __path__ (which is legal, but weird)
        # fails silently. Try with dirname of module file if __path__ attribute
        # is not present.
        app_module = import_module(app)
        if hasattr(app_module, '__path__'):
            app_path = app_module.__path__
        else:
            app_path = dirname(app_module.__file__)

        # Step 2: use imp.find_module to find the app's `module_name`. For some
        # reason imp.find_module raises ImportError if the app can't be found
        # but doesn't actually try to import the module. So skip this app if
        # its `module_name` doesn't exist
        try:
            imp.find_module(module_name, app_path)
        except ImportError, e:
            continue

        # Step 3: import the app's translation file. If this has errors we want them
        # to bubble up.
        import_module('.'.join([app, module_name]))
예제 #6
0
            imp.find_module(module_name, app_path)
        except ImportError, e:
            continue

        # Step 3: import the app's translation file.
        # If this has errors we want them to bubble up.
        import_module('.'.join([app, module_name]))

    from model_i18n import translator
    from model_i18n.conf import TRANSLATED_APP_MODELS
    from django.core.exceptions import ImproperlyConfigured

    for app_path in TRANSLATED_APP_MODELS:
        model_conf = TRANSLATED_APP_MODELS[app_path]
        for model_name in model_conf:
            model_module = import_module(app_path + '.models')
            try:
                django_model = getattr(model_module, model_name)
            except:
                raise ImproperlyConfigured("Model %s does not exist on %s" % \
                    (model_name, app_path))
            translator.register(django_model, **model_conf[model_name])


def autodiscover_admin(adminsite=None):

    if not adminsite:
        from django.contrib.admin import site
        adminsite = site

    from model_i18n.translator import _translator
예제 #7
0
    def register(self, master_model, translation_class=None, **options):
        if type(master_model) is str:
            app_path = ".".join(master_model.split(".")[:-1])
            master_module_models = import_module(app_path + '.models')
            master_model = getattr(master_module_models,
                                   master_model.split(".")[-1])
        if master_model in self._registry:
            raise AlreadyRegistered('The model "%s" has is already \
            registered for translation' % master_model.__name__)

        # If not translation_class given use default options.
        if not translation_class:
            translation_class = ModelTranslation

        # If we got **options then dynamically construct a
        # subclass of translation_class with those **options.
        if options:
            translation_class = type('%sTranslation' % \
            master_model.__name__, (translation_class,), options)

        # Validate the translation_class (just in debug mode).
        if settings.DEBUG:
            from model_i18n.validation import validate
            validate(translation_class, master_model)

        transmanager_class = type('%sTransManager' % master_model.__name__, (
            TransManager,
            master_model.objects.__class__,
        ), {})
        try:
            livetransmanager_class = type(
                '%sLiveTransManager' % master_model.__name__, (
                    TransManager,
                    master_model.live_objects.__class__,
                ), {})
        except:
            livetransmanager_class = type(
                '%sLiveTransManager' % master_model.__name__, (
                    TransManager,
                    master_model.objects.__class__,
                ), {})

        master_model.add_to_class('_default_manager', TransManager())
        master_model.add_to_class('_base_manager', TransManager())
        master_model.add_to_class('objects', transmanager_class())
        master_model.add_to_class('live_objects', livetransmanager_class())

        opts = translation_class(master_model)

        # Set up master_model as a multilingual model
        # using translation_class options
        tmodel = self.create_translation_model(master_model, opts)
        tmodel.__unicode__ = lambda s: unicode(
            getattr(s, s._transmeta.master_field_name))
        # defaults = {'blank': True, 'null': True, 'editable': False, 'related_name': '%(app_label)s_%(class)s_related'}
        # m2mfield = models.ManyToManyField(tmodel, **defaults)
        # master_model.add_to_class("translations", m2mfield)

        # This probably will become a class method soon.
        self.setup_master_model(master_model, tmodel)
        if MODEL_I18N_DJANGO_ADMIN:
            self._registry_admin[master_model] = tmodel

        # Register the multilingual model and the used translation_class.
        self._registry[master_model] = opts
예제 #8
0
def autodiscover(module_name=None):

    """
    Auto-discover translations.py files in installed app's directories, fail
    silently if not present. This forces an import on them to register any
    translation bits they may want.

    Based on django's contrib.admin autodiscover().
    """

    import imp
    from model_i18n.utils import import_module
    from model_i18n.conf import settings

    if not module_name:
        module_name = settings.TRANSLATION_FILENAMES or 'translations'

    for app in settings.INSTALLED_APPS:
        if app == 'model_i18n':
            continue
        # For each app, we need to look for `module_name` in that app's
        # package. We can't use os.path here -- recall that modules may be
        # imported different ways (think zip files) -- so we need to get
        # the app's __path__ and look for translation.py on that path.

        # Step 1: find out the app's __path__ Import errors here will (and
        # should) bubble up, but a missing __path__ (which is legal, but weird)
        # fails silently. Try with dirname of module file if __path__ attribute
        # is not present.
        app_module = import_module(app)
        if hasattr(app_module, '__path__'):
            app_path = app_module.__path__
        else:
            app_path = path.dirname(app_module.__file__)

        # Step 2: use imp.find_module to find the app's `module_name`. For some
        # reason imp.find_module raises ImportError if the app can't be found
        # but doesn't actually try to import the module. So skip this app if
        # its `module_name` doesn't exist

        try:
            imp.find_module(module_name, app_path)
        except ImportError:
            continue
        # Step 3: import the app's translation file.
        # If this has errors we want them to bubble up.
        import_module('.'.join([app, module_name]))

    if settings.MODEL_I18N_SETTINGS_PATH:
        project_dir = settings.MODEL_I18N_SETTINGS_PATH
    else:
        project_dir = path.dirname(import_module(settings.SETTINGS_MODULE).__file__)
    project_folder = path.basename(project_dir)
    try:

        imp.find_module(module_name, [project_dir, ])
        import_module('.'.join([project_folder, module_name]))
    except ImportError:
        pass

    from model_i18n import translator
    from model_i18n.conf import TRANSLATED_APP_MODELS
    from django.core.exceptions import ImproperlyConfigured

    if TRANSLATED_APP_MODELS:
        for app_path in TRANSLATED_APP_MODELS:
            model_conf = TRANSLATED_APP_MODELS[app_path]
            for model_name in model_conf:
                model_module = import_module(app_path + '.models')
                try:
                    django_model = getattr(model_module, model_name)
                except:
                    raise ImproperlyConfigured("Model %s does not exist on %s" % \
                        (model_name, app_path))
                if django_model not in translator._translator._registry:
                    translator.register(django_model, **model_conf[model_name])