Python django.conf.settings.LOCALE_PATHS Examples

The following are 30 code examples for showing how to use django.conf.settings.LOCALE_PATHS(). These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.

You may check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module django.conf.settings , or try the search function .

Example 1
Project: django-autotranslate   Author: ankitpopli1891   File: translate_messages.py    License: MIT License 6 votes vote down vote up
def handle(self, *args, **options):
        self.set_options(**options)

        assert getattr(settings, 'USE_I18N', False), 'i18n framework is disabled'
        assert getattr(settings, 'LOCALE_PATHS', []), 'locale paths is not configured properly'
        for directory in settings.LOCALE_PATHS:
            # walk through all the paths
            # and find all the pot files
            for root, dirs, files in os.walk(directory):
                for file in files:
                    if not file.endswith('.po'):
                        # process file only
                        # if its a pot file
                        continue

                    # get the target language from the parent folder name
                    target_language = os.path.basename(os.path.dirname(root))

                    if self.locale and target_language not in self.locale:
                        logger.info('skipping translation for locale `{}`'.format(target_language))
                        continue

                    self.translate_file(root, file, target_language) 
Example 2
Project: GTDWeb   Author: lanbing510   File: trans_real.py    License: GNU General Public License v2.0 5 votes vote down vote up
def _add_local_translations(self):
        """Merges translations defined in LOCALE_PATHS."""
        for localedir in reversed(settings.LOCALE_PATHS):
            translation = self._new_gnu_trans(localedir)
            self.merge(translation) 
Example 3
Project: GTDWeb   Author: lanbing510   File: trans_real.py    License: GNU General Public License v2.0 5 votes vote down vote up
def all_locale_paths():
    """
    Returns a list of paths to user-provides languages files.
    """
    globalpath = os.path.join(
        os.path.dirname(upath(sys.modules[settings.__module__].__file__)), 'locale')
    return [globalpath] + list(settings.LOCALE_PATHS) 
Example 4
Project: bioforum   Author: reBiocoder   File: trans_real.py    License: MIT License 5 votes vote down vote up
def _add_local_translations(self):
        """Merge translations defined in LOCALE_PATHS."""
        for localedir in reversed(settings.LOCALE_PATHS):
            translation = self._new_gnu_trans(localedir)
            self.merge(translation) 
Example 5
Project: bioforum   Author: reBiocoder   File: trans_real.py    License: MIT License 5 votes vote down vote up
def all_locale_paths():
    """
    Return a list of paths to user-provides languages files.
    """
    globalpath = os.path.join(
        os.path.dirname(sys.modules[settings.__module__].__file__), 'locale')
    return [globalpath] + list(settings.LOCALE_PATHS) 
Example 6
Project: django-pyqt   Author: ZedObaia   File: manage.py    License: MIT License 5 votes vote down vote up
def deploy():
    hidden_imports = ['http.cookies', 'html.parser',
                      'settings', 'apps', 'django.template.defaulttags',
                      'django.templatetags.i18n', 'django.template.loader_tags',
                      'django.utils.translation'
                      ]
    for app in settings.INSTALLED_APPS:
        if app.startswith('django.'):
            hidden_imports.append(app + '.apps')
        else:
            hidden_imports.append(app)

            cmd = "pyinstaller __main__.py "
    for i in hidden_imports:
        cmd += " --hidden-import "
        cmd += i

    os.system(cmd)
    if settings.DATABASES['default']['ENGINE'] == 'django.db.backends.sqlite3':
        dist_dir = os.path.join(os.path.join(settings.BASE_DIR, 'dist'), '__main__')
        if os.path.isdir(dist_dir):
            shutil.copy(settings.DATABASES['default']['NAME'], dist_dir)
    if settings.LANGUAGES is not None:
        for lang in settings.LANGUAGES:
            execute_django_command(["makemessages", "-l", lang[0]])
        execute_django_command(["compilemessages"])
        try:
            shutil.copytree(settings.LOCALE_PATHS[0], os.path.join(dist_dir, '.locale'))
        except Exception as e:
            print(e) 
Example 7
Project: django-pyqt   Author: ZedObaia   File: manage.py    License: MIT License 5 votes vote down vote up
def deploy():
    hidden_imports = ['http.cookies', 'html.parser',
                      'settings', 'apps', 'django.template.defaulttags',
                      'django.templatetags.i18n', 'django.template.loader_tags',
                      'django.utils.translation'
                      ]
    for app in settings.INSTALLED_APPS:
        if app.startswith('django.'):
            hidden_imports.append(app + '.apps')
        else:
            hidden_imports.append(app)

            cmd = "pyinstaller __main__.py "
    for i in hidden_imports:
        cmd += " --hidden-import "
        cmd += i

    os.system(cmd)
    if settings.DATABASES['default']['ENGINE'] == 'django.db.backends.sqlite3':
        dist_dir = os.path.join(os.path.join(settings.BASE_DIR, 'dist'), '__main__')
        if os.path.isdir(dist_dir):
            shutil.copy(settings.DATABASES['default']['NAME'], dist_dir)
    if settings.LANGUAGES is not None:
        for lang in settings.LANGUAGES:
            execute_django_command(["makemessages", "-l", lang[0]])
        execute_django_command(["compilemessages"])
        try:
            shutil.copytree(settings.LOCALE_PATHS[0], os.path.join(dist_dir, '.locale'))
        except Exception as e:
            print(e) 
Example 8
Project: django-pyqt   Author: ZedObaia   File: manage.py    License: MIT License 5 votes vote down vote up
def deploy():
    if not os.path.isfile(configFile):
        print("Missing config.json")
        hidden_imports = []
    else:
        with open(configFile) as f:
            config = json.load(f)
        hidden_imports = config["hidden-imports"]
    if config["django"] :
        for app in settings.INSTALLED_APPS:
            if app.startswith('django.'):
                hidden_imports.append(app + '.apps')
            else:
                hidden_imports.append(app)

    cmd = "pyinstaller __main__.py "
    for i in hidden_imports:
        cmd += " --hidden-import "
        cmd += i

    os.system(cmd)
    if config["django"]:
        dist_dir = os.path.join(os.path.join(settings.BASE_DIR, 'dist'), '__main__')
        if settings.DATABASES['default']['ENGINE'] == 'django.db.backends.sqlite3':
            if os.path.isfile(settings.DATABASES['default']['NAME']) :
                if os.path.isdir(dist_dir):
                    shutil.copy(settings.DATABASES['default']['NAME'], dist_dir)
            else:
                print("{} was not found".format(settings.DATABASES['default']['NAME'])  )
        if settings.LANGUAGES is not None:
            for lang in settings.LANGUAGES:
                execute_django_command(["makemessages", "-l", lang[0]])
            execute_django_command(["compilemessages"])
            try:
                shutil.copytree(settings.LOCALE_PATHS[0], os.path.join(dist_dir, '.locale'))
            except Exception as e:
                print(e) 
Example 9
Project: Hands-On-Application-Development-with-PyCharm   Author: PacktPublishing   File: trans_real.py    License: MIT License 5 votes vote down vote up
def _add_local_translations(self):
        """Merge translations defined in LOCALE_PATHS."""
        for localedir in reversed(settings.LOCALE_PATHS):
            translation = self._new_gnu_trans(localedir)
            self.merge(translation) 
Example 10
Project: Hands-On-Application-Development-with-PyCharm   Author: PacktPublishing   File: trans_real.py    License: MIT License 5 votes vote down vote up
def all_locale_paths():
    """
    Return a list of paths to user-provides languages files.
    """
    globalpath = os.path.join(
        os.path.dirname(sys.modules[settings.__module__].__file__), 'locale')
    app_paths = []
    for app_config in apps.get_app_configs():
        locale_path = os.path.join(app_config.path, 'locale')
        if os.path.exists(locale_path):
            app_paths.append(locale_path)
    return [globalpath] + list(settings.LOCALE_PATHS) + app_paths 
Example 11
Project: python   Author: Yeah-Kun   File: trans_real.py    License: Apache License 2.0 5 votes vote down vote up
def _add_local_translations(self):
        """Merges translations defined in LOCALE_PATHS."""
        for localedir in reversed(settings.LOCALE_PATHS):
            translation = self._new_gnu_trans(localedir)
            self.merge(translation) 
Example 12
Project: python   Author: Yeah-Kun   File: trans_real.py    License: Apache License 2.0 5 votes vote down vote up
def all_locale_paths():
    """
    Returns a list of paths to user-provides languages files.
    """
    globalpath = os.path.join(
        os.path.dirname(upath(sys.modules[settings.__module__].__file__)), 'locale')
    return [globalpath] + list(settings.LOCALE_PATHS) 
Example 13
Project: luscan-devel   Author: blackye   File: trans_real.py    License: GNU General Public License v2.0 5 votes vote down vote up
def all_locale_paths():
    """
    Returns a list of paths to user-provides languages files.
    """
    from django.conf import settings
    globalpath = os.path.join(
        os.path.dirname(upath(sys.modules[settings.__module__].__file__)), 'locale')
    return [globalpath] + list(settings.LOCALE_PATHS) 
Example 14
Project: luscan-devel   Author: blackye   File: compilemessages.py    License: GNU General Public License v2.0 5 votes vote down vote up
def compile_messages(stderr, locale=None):
    basedirs = [os.path.join('conf', 'locale'), 'locale']
    if os.environ.get('DJANGO_SETTINGS_MODULE'):
        from django.conf import settings
        basedirs.extend(settings.LOCALE_PATHS)

    # Gather existing directories.
    basedirs = set(map(os.path.abspath, filter(os.path.isdir, basedirs)))

    if not basedirs:
        raise CommandError("This script should be run from the Django Git checkout or your project or app tree, or with the settings module specified.")

    for basedir in basedirs:
        if locale:
            basedir = os.path.join(basedir, locale, 'LC_MESSAGES')
        for dirpath, dirnames, filenames in os.walk(basedir):
            for f in filenames:
                if f.endswith('.po'):
                    stderr.write('processing file %s in %s\n' % (f, dirpath))
                    fn = os.path.join(dirpath, f)
                    if has_bom(fn):
                        raise CommandError("The %s file has a BOM (Byte Order Mark). Django only supports .po files encoded in UTF-8 and without any BOM." % fn)
                    pf = os.path.splitext(fn)[0]
                    # Store the names of the .mo and .po files in an environment
                    # variable, rather than doing a string replacement into the
                    # command, so that we can take advantage of shell quoting, to
                    # quote any malicious characters/escaping.
                    # See http://cyberelk.net/tim/articles/cmdline/ar01s02.html
                    os.environ['djangocompilemo'] = npath(pf + '.mo')
                    os.environ['djangocompilepo'] = npath(pf + '.po')
                    if sys.platform == 'win32': # Different shell-variable syntax
                        cmd = 'msgfmt --check-format -o "%djangocompilemo%" "%djangocompilepo%"'
                    else:
                        cmd = 'msgfmt --check-format -o "$djangocompilemo" "$djangocompilepo"'
                    os.system(cmd) 
Example 15
Project: openhgsenti   Author: drexly   File: trans_real.py    License: Apache License 2.0 5 votes vote down vote up
def _add_local_translations(self):
        """Merges translations defined in LOCALE_PATHS."""
        for localedir in reversed(settings.LOCALE_PATHS):
            translation = self._new_gnu_trans(localedir)
            self.merge(translation) 
Example 16
Project: openhgsenti   Author: drexly   File: trans_real.py    License: Apache License 2.0 5 votes vote down vote up
def all_locale_paths():
    """
    Returns a list of paths to user-provides languages files.
    """
    globalpath = os.path.join(
        os.path.dirname(upath(sys.modules[settings.__module__].__file__)), 'locale')
    return [globalpath] + list(settings.LOCALE_PATHS) 
Example 17
def set_rels(apps, schema_editor):
    TranslationEntry = apps.get_model('translation_manager', 'TranslationEntry')
    for row in TranslationEntry.objects.all():
        row.locale_path = os.path.relpath(settings.LOCALE_PATHS[0], get_settings('TRANSLATIONS_BASE_DIR'))
        row.save()

    TranslationBackup = apps.get_model('translation_manager', 'TranslationBackup')
    for row in TranslationBackup.objects.all():
        row.locale_path = os.path.relpath(settings.LOCALE_PATHS[0], get_settings('TRANSLATIONS_BASE_DIR'))
        row.save() 
Example 18
Project: django-translation-manager   Author: COEXCZ   File: manager.py    License: Mozilla Public License 2.0 5 votes vote down vote up
def backup_po_to_db(self):
        """ Backup Po file to db model """

        for lang, lang_name in settings.LANGUAGES:
            for path in settings.LOCALE_PATHS:
                po_pattern = os.path.join(path, get_dirname_from_lang(lang), "LC_MESSAGES", "*.po")
                for pofile in glob(po_pattern):
                    logger.debug("Backuping file {} to db".format(pofile))

                    domain = os.path.splitext(os.path.basename(pofile))[0]
                    with codecs.open(pofile, 'r', 'utf-8') as pofile_opened:
                        content = pofile_opened.read()
                        backup = TranslationBackup(
                            language=lang,
                            locale_path=get_relative_locale_path(pofile),
                            domain=domain,
                            locale_parent_dir=get_locale_parent_dirname(pofile),
                            content=content,
                        )
                        backup.save()

                    if get_settings('TRANSLATIONS_CLEAN_PO_AFTER_BACKUP'):
                        with open(pofile, 'w') as pofile_opened:
                            pofile_opened.write('')

    ############################################################################ 
Example 19
Project: django-translation-manager   Author: COEXCZ   File: manager.py    License: Mozilla Public License 2.0 5 votes vote down vote up
def load_data_from_po(self):
        import os

        for lang, lang_name in settings.LANGUAGES:
            for path in settings.LOCALE_PATHS:
                locale = get_dirname_from_lang(lang)
                po_pattern = os.path.join(path, locale, "LC_MESSAGES", "*.po")
                for pofile in glob(po_pattern):
                    logger.debug("Processing pofile {}".format(pofile))
                    self.store_to_db(pofile=pofile, locale=locale, store_translations=True)

        self.postprocess() 
Example 20
Project: python2017   Author: bpgc-cte   File: trans_real.py    License: MIT License 5 votes vote down vote up
def _add_local_translations(self):
        """Merges translations defined in LOCALE_PATHS."""
        for localedir in reversed(settings.LOCALE_PATHS):
            translation = self._new_gnu_trans(localedir)
            self.merge(translation) 
Example 21
Project: python2017   Author: bpgc-cte   File: trans_real.py    License: MIT License 5 votes vote down vote up
def all_locale_paths():
    """
    Returns a list of paths to user-provides languages files.
    """
    globalpath = os.path.join(
        os.path.dirname(upath(sys.modules[settings.__module__].__file__)), 'locale')
    return [globalpath] + list(settings.LOCALE_PATHS) 
Example 22
Project: ecommerce   Author: edx   File: core.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def enable_theming():
    """
        Add directories and relevant paths to settings for comprehensive theming.
    """
    for theme in get_themes():
        locale_dir = theme.path / "conf" / "locale"
        if locale_dir.isdir():
            settings.LOCALE_PATHS = (locale_dir, ) + settings.LOCALE_PATHS 
Example 23
Project: ecommerce   Author: edx   File: test_core.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def test_enable_theming(self):
        """
        Tests for enable_theming method.
        """
        themes_dirs = settings.COMPREHENSIVE_THEME_DIRS

        expected_locale_paths = (
            themes_dirs[0] / "test-theme" / "conf" / "locale",
            themes_dirs[0] / "test-theme-2" / "conf" / "locale",
            themes_dirs[1] / "test-theme-3" / "conf" / "locale",
        ) + settings.LOCALE_PATHS

        enable_theming()

        six.assertCountEqual(self, expected_locale_paths, settings.LOCALE_PATHS) 
Example 24
Project: ecommerce   Author: edx   File: test_core.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def test_enable_theming_red_theme(self):
        """
        Tests that locale path is added only if it exists.
        """
        # Themes directory containing red-theme
        themes_dir = settings.DJANGO_ROOT + "/themes"

        # Note: red-theme does not contain translations dir
        red_theme = Path(themes_dir + "/red-theme")
        with override_settings(COMPREHENSIVE_THEME_DIRS=[red_theme.dirname()]):
            enable_theming()

            # Test that locale path is added only if it exists
            self.assertNotIn(red_theme / "conf" / "locale", settings.LOCALE_PATHS) 
Example 25
Project: ecommerce   Author: edx   File: test_apps.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def test_theme_config_ready(self):
        """
        Tests enable theming is called in app config's ready method.
        """
        themes_dirs = settings.COMPREHENSIVE_THEME_DIRS

        # make sure locale paths were added to LOCALE_PATHS setting
        self.assertIn(themes_dirs[0] / "test-theme" / "conf" / "locale", settings.LOCALE_PATHS)
        self.assertIn(themes_dirs[0] / "test-theme-2" / "conf" / "locale", settings.LOCALE_PATHS)

        self.assertIn(themes_dirs[1] / "test-theme-3" / "conf" / "locale", settings.LOCALE_PATHS) 
Example 26
Project: djongo   Author: nesdis   File: test_i18n.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def test_i18n_with_locale_paths(self):
        extended_locale_paths = settings.LOCALE_PATHS + [
            path.join(
                path.dirname(path.dirname(path.abspath(__file__))),
                'app3',
                'locale',
            ),
        ]
        with self.settings(LANGUAGE_CODE='es-ar', LOCALE_PATHS=extended_locale_paths):
            with override('es-ar'):
                response = self.client.get('/jsi18n/')
                self.assertContains(response, 'este texto de app3 debe ser traducido') 
Example 27
Project: djongo   Author: nesdis   File: tests.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def test_locale_paths_translation(self):
        self.assertGettext('Time', 'LOCALE_PATHS') 
Example 28
Project: djongo   Author: nesdis   File: tests.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def test_locale_paths_override_app_translation(self):
        with self.settings(INSTALLED_APPS=['i18n.resolution']):
            self.assertGettext('Time', 'LOCALE_PATHS') 
Example 29
Project: djongo   Author: nesdis   File: test_i18n.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def test_i18n_with_locale_paths(self):
        extended_locale_paths = settings.LOCALE_PATHS + [
            path.join(
                path.dirname(path.dirname(path.abspath(__file__))),
                'app3',
                'locale',
            ),
        ]
        with self.settings(LANGUAGE_CODE='es-ar', LOCALE_PATHS=extended_locale_paths):
            with override('es-ar'):
                response = self.client.get('/jsi18n/')
                self.assertContains(response, 'este texto de app3 debe ser traducido') 
Example 30
Project: GTDWeb   Author: lanbing510   File: autoreload.py    License: GNU General Public License v2.0 4 votes vote down vote up
def gen_filenames(only_new=False):
    """
    Returns a list of filenames referenced in sys.modules and translation
    files.
    """
    # N.B. ``list(...)`` is needed, because this runs in parallel with
    # application code which might be mutating ``sys.modules``, and this will
    # fail with RuntimeError: cannot mutate dictionary while iterating
    global _cached_modules, _cached_filenames
    module_values = set(sys.modules.values())
    _cached_filenames = clean_files(_cached_filenames)
    if _cached_modules == module_values:
        # No changes in module list, short-circuit the function
        if only_new:
            return []
        else:
            return _cached_filenames

    new_modules = module_values - _cached_modules
    new_filenames = clean_files(
        [filename.__file__ for filename in new_modules
         if hasattr(filename, '__file__')])

    if not _cached_filenames and settings.USE_I18N:
        # Add the names of the .mo files that can be generated
        # by compilemessages management command to the list of files watched.
        basedirs = [os.path.join(os.path.dirname(os.path.dirname(__file__)),
                                 'conf', 'locale'),
                    'locale']
        for app_config in reversed(list(apps.get_app_configs())):
            basedirs.append(os.path.join(app_config.path, 'locale'))
        basedirs.extend(settings.LOCALE_PATHS)
        basedirs = [os.path.abspath(basedir) for basedir in basedirs
                    if os.path.isdir(basedir)]
        for basedir in basedirs:
            for dirpath, dirnames, locale_filenames in os.walk(basedir):
                for filename in locale_filenames:
                    if filename.endswith('.mo'):
                        new_filenames.append(os.path.join(dirpath, filename))

    _cached_modules = _cached_modules.union(new_modules)
    _cached_filenames += new_filenames
    if only_new:
        return new_filenames
    else:
        return _cached_filenames + clean_files(_error_files)