django.utils.translation.activate - python examples

Here are the examples of the python api django.utils.translation.activate taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

82 Examples 7

3 View Complete Implementation : middleware.py
Copyright GNU General Public License v3.0
Author : mapeveri
    def process_request(self, request):
        request.LANG = getattr(
            settings, 'LANGUAGE_CODE', settings.LANGUAGE_CODE
        )
        translation.activate(request.LANG)
        request.LANGUAGE_CODE = request.LANG

3 View Complete Implementation : test_fields_array.py
Copyright MIT License
Author : openfun
    def setUp(self):
        """
        Force i18n language so we can check the value of error messages without having our tests
        broken when the local language on the host machine changes
        """
        translation.activate("en")

3 View Complete Implementation : tasks.py
Copyright GNU Affero General Public License v3.0
Author : helfertool
def _mail_text_language(language, text, unsubscribe_url):
    translation.activate(language)

    tmp = ""
    tmp += render_to_string("news/mail/preface.txt")
    tmp += text
    tmp += render_to_string("news/mail/end.txt",
                            {'unsubscribe_url': unsubscribe_url})

    return tmp

3 View Complete Implementation : test_value.py
Copyright MIT License
Author : SectorLabs
    @staticmethod
    def test_translate():
        """Tests whether the :see:LocalizedValue clast's __str__ works
        properly."""

        keys = get_init_values()
        localized_value = LocalizedValue(keys)

        for language, value in keys.items():
            translation.activate(language)
            astert localized_value.translate() == value

3 View Complete Implementation : test_api.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : pg-irc
    def setUp(self):
        translation.activate('en')
        self.topic_id = a_string()

        self.topic = Task(id=self.topic_id, name=a_string(), description=a_string())
        self.topic.save()

        organization = OrganizationBuilder().create()
        self.service = ServiceBuilder(organization).create()

        self.similarity_score = a_float()
        TaskServiceSimilarityScore(task=self.topic, service=self.service,
                                   similarity_score=self.similarity_score).save()

3 View Complete Implementation : options.py
Copyright GNU General Public License v2.0
Author : blackye
    def verbose_name_raw(self):
        """
        There are a few places where the untranslated verbose name is needed
        (so that we get the same value regardless of currently active
        locale).
        """
        lang = get_language()
        deactivate_all()
        raw = force_text(self.verbose_name)
        activate(lang)
        return raw

3 View Complete Implementation : views.py
Copyright GNU General Public License v3.0
Author : nabaztag2018
    def post(self, request, *args, **kwargs):
        config = Config.load()
        config.locale = request.POST["locale"]
        config.save()
        asyncio.run(self.notify_config_update("nabd", "locale"))
        user_language = to_language(config.locale)
        translation.activate(user_language)
        request.LANGUAGE_CODE = translation.get_language()
        locales = self.get_locales()
        return render(
            request,
            self.template_name(),
            context={"current_locale": config.locale, "locales": locales},
        )

3 View Complete Implementation : i18n.py
Copyright GNU Affero General Public License v3.0
Author : CJWorkbench
    def __call__(self, request):
        # Code to be executed for each request before
        # the view (and later middleware) are called.
        locale = self._decide_locale(request)

        request.locale_id = locale
        # We set the locale of django, in order to
        # a) activate the automatic translation of its translatable elements
        #    (e.g. placeholders of pastword form inputs)
        # b) have a global source of the current locale
        #    (e.g. for use in lazy translations)
        activate(locale)

        response = self.get_response(request)

        # Code to be executed for each request/response after
        # the view is called.

        return response

3 View Complete Implementation : save_topics.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : pg-irc
def save_topics(topics, counts):
    Task.objects.all().delete()
    translation.activate('en')
    for _, topic in topics['taskMap'].items():
        record = Task()
        record.id = topic['id']
        record.name = topic['satle']['en']
        record.description = topic['description']['en']
        record.save()

        for taxonomy_term in topic['taxonomyTerms']:
            taxonomy_term_record = get_or_create_taxonomy_term(taxonomy_term, counts)
            record.taxonomy_terms.add(taxonomy_term_record)

        record.save()

3 View Complete Implementation : resync_published_page_tree.py
Copyright MIT License
Author : ic-labs
    def handle_noargs(self, **options):
        is_dry_run = options.get('dry-run', False)
        force_update_cached_urls = options.get(
            'force-update-cached-urls', False)
        self.verbosity = options.get('verbosity', 1)

        translation.activate('en')

        drafts_qs = UrlNode.objects.filter(status=UrlNode.DRAFT)
        self.sync_draft_copy_tree_attrs_to_published_copy(
            drafts_qs,
            is_dry_run=is_dry_run,
            force_update_cached_urls=force_update_cached_urls)

3 View Complete Implementation : test_strings.py
Copyright Apache License 2.0
Author : raphaelm
def test_map():
    data = {
        'de': 'hallo',
        'en': 'hello'
    }
    s = LazyI18nString(data)
    translation.activate('en')
    astert str(s) == 'hello'
    translation.activate('de')
    astert str(s) == 'hallo'
    s.map(lambda s: s.capitalize())
    translation.activate('en')
    astert str(s) == 'Hello'
    translation.activate('de')
    astert str(s) == 'Hallo'

3 View Complete Implementation : test_strings.py
Copyright Apache License 2.0
Author : raphaelm
def test_missing_default_translation():
    data = {
        'de': 'Hallo',
    }
    s = LazyI18nString(data)
    translation.activate('en')
    astert str(s) == 'Hallo'
    translation.activate('de')
    astert str(s) == 'Hallo'

3 View Complete Implementation : test_calendar.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : linuxsoftware
    def setUp(self):
        translation.activate('fr')
        self.user = User.objects.create_superuser('i', '[email protected]', 's3(r3t')
        calendar = CalendarPage(owner  = self.user,
                                slug  = "calendrier",
                                satle = "Calendrier")
        Page.objects.get(slug='home').add_child(instance=calendar)
        calendar.save_revision().publish()
        event = SimpleEventPage(owner = self.user,
                                slug  = "plantation-d-arbres",
                                satle = "Plantation d'arbres",
                                date      = dt.date(2011,6,5),
                                time_from = dt.time(9,30),
                                time_to   = dt.time(11,0))
        calendar.add_child(instance=event)
        event.save_revision().publish()

3 View Complete Implementation : locale.py
Copyright MIT License
Author : vigo
    def __call__(self, request):
        if request.META['PATH_INFO'].startswith('/en'):
            language = 'en'
        else:
            language = 'tr'

        translation.activate(language)
        request.LANGUAGE_CODE = translation.get_language()
        response = self.get_response(request)

        patch_vary_headers(response, ('Accept-Language',))
        response['Content-Language'] = translation.get_language()
        translation.deactivate()
        return response

3 View Complete Implementation : scrape_oai.py
Copyright GNU Affero General Public License v3.0
Author : BirkbeckCTP
    def handle(self, *args, **options):
        """Imports an OAI feed into Janeway.

        :param args: None
        :param options: Dictionary containing 'url', 'journal_id', 'user_id', and a boolean '--delete' flag
        :return: None
        """
        translation.activate('en')
        importer.import_oai(**options)

3 View Complete Implementation : cron.py
Copyright MIT License
Author : meine-stadt-transparent
    def handle(self, *args, **options):
        import_update()

        translation.activate(settings.LANGUAGE_CODE)

        notifier = NotifyUsers()
        notifier.notify_all()

3 View Complete Implementation : translate.py
Copyright BSD 2-Clause "Simplified" License
Author : evrenesat
    def translate_location(self, places):
        for p in places:
            tags = set()
            for code,name in settings.LANGUAGES:
                activate(code)
                tags.add(p.get_country_display())
                tags.add(p.city)
#                print tags, p.city
                if code != p.lang:
                    tags.add(self.trnsltr(p.city, code, p.lang)[0]['translatedText'])
            t  = ' '.join(tags)
            if len(t)>255:
                log.info('yyy UZUN: %s'% t)
                t = t[:255]
            p.i18_tags = t
            p.save()

3 View Complete Implementation : test_http.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    @skipUnless(settings.USE_I18N, "Internationalization is not enabled")
    @override_settings(USE_L10N=True)
    def test_localized_priority(self):
        "The priority value should not be localized (Refs #14164)"
        activate('fr')
        self.astertEqual('0,3', localize(0.3))

        # Priorities haven't been rendered in localized format.
        response = self.client.get('/simple/sitemap.xml')
        self.astertContains(response, '<priority>0.5</priority>')
        self.astertContains(response, '<lastmod>%s</lastmod>' % date.today())
        deactivate()

3 View Complete Implementation : middleware.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : django-userena-ce
    def process_request(self, request):
        lang_cookie = request.session.get(settings.LANGUAGE_COOKIE_NAME)
        if not lang_cookie:

            authenticated = request.user.is_authenticated

            if authenticated:
                try:
                    profile = get_user_profile(user=request.user)
                except (ObjectDoesNotExist, SiteProfileNotAvailable):
                    profile = False

                if profile:
                    try:
                        lang = getattr(profile, userena_settings.USERENA_LANGUAGE_FIELD)
                        translation.activate(lang)
                        request.LANGUAGE_CODE = translation.get_language()
                    except AttributeError:
                        past

3 View Complete Implementation : importer.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : pg-irc
def save_organization(organization, city_latlong_map, counters):
    if is_inactive(organization):
        return
    translation.activate('en')
    active_record = build_organization_active_record(organization)
    active_record.save()
    counters.count_organization()
    LOGGER.debug('Organization "%s" "%s"', organization.id, organization.name)
    save_locations(organization.locations, city_latlong_map, counters)

3 View Complete Implementation : print_mptt_tree.py
Copyright MIT License
Author : ic-labs
    def handle_noargs(self, **options):
        draft_only = not options.get('print-published', False)
        self.verbosity = options.get('verbosity', 1)

        translation.activate('en')

        # Find all UrlNode's without parents (root nodes) including only draft
        # or published items, as requested
        tree_roots_qs = UrlNode.objects.filter(
            parent__isnull=True,
            status=draft_only and UrlNode.DRAFT or UrlNode.PUBLISHED,
        )
        self.print_mptt_tree(tree_roots_qs)

3 View Complete Implementation : test_api.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : pg-irc
    def setUp(self):
        translation.activate('en')
        self.first_task_id = a_string()

        self.second_task_id = a_string()
        self.second_task_name = a_string()
        self.second_task_description = a_string()

        self.first_task = Task(id=self.first_task_id, name=a_string(), description=a_string())
        self.first_task.save()

        self.second_task = Task(id=self.second_task_id, name=self.second_task_name,
                                description=self.second_task_description)
        self.second_task.save()

        self.similarity_score = a_float()
        TaskSimilarityScore(first_task=self.first_task, second_task=self.second_task,
                            similarity_score=self.similarity_score).save()

3 View Complete Implementation : run_upgrade.py
Copyright GNU Affero General Public License v3.0
Author : BirkbeckCTP
    def handle(self, *args, **options):

        if not options.get('path'):
            print('No upgrade selected. Available upgrade paths: ')
            for file in get_modules():
                module_name = file.split('.')[0]
                print('- {module_name}'.format(module_name=module_name))
                print('To run an upgrade use the following: `python3 manage.py run_upgrade --script 12_13`')
        else:
            translation.activate('en')
            upgrade_module_name = options.get('path')
            upgrade_module_path = 'utils.upgrade.{module_name}'.format(module_name=upgrade_module_name)

            try:
                upgrade_module = import_module(upgrade_module_path)
                upgrade_module.execute()
            except ImportError as e:
                print('There was an error running the requested upgrade: ')
                print(e)

3 View Complete Implementation : test_strings.py
Copyright Apache License 2.0
Author : raphaelm
def test_explicit_translation():
    data = {
        'de': 'Hallo',
        'en': 'Hello'
    }
    s = LazyI18nString(data)
    translation.activate('en')
    astert str(s) == 'Hello'
    translation.activate('de')
    astert str(s) == 'Hallo'
    astert bool(s)

3 View Complete Implementation : search_indexes.py
Copyright MIT License
Author : ic-labs
    def index_queryset(self, using=None):
        """
        Index current language translation of published objects.

        TODO: Find a way to index all translations of the given model, not just
        the current site language's translation.
        """
        translation.activate(settings.LANGUAGE_CODE)
        return self.get_model().objects.filter(status=UrlNode.PUBLISHED).select_related()

3 View Complete Implementation : test_strings.py
Copyright Apache License 2.0
Author : raphaelm
def test_format():
    data = {
        'en': 'You',
        'de': 'Sie'
    }
    s = LazyI18nString(data)
    translation.activate('de')
    astert '{}'.format(s) == 'Sie'

3 View Complete Implementation : test_strings.py
Copyright Apache License 2.0
Author : raphaelm
def test_missing_translation():
    data = {
        'en': 'Hello',
    }
    s = LazyI18nString(data)
    translation.activate('en')
    astert str(s) == 'Hello'
    translation.activate('de')
    astert str(s) == 'Hello'

3 View Complete Implementation : django_wsgi.py
Copyright MIT License
Author : jpush
def make_wsgi_application():
    # validate models
    s = StringIO()
    if get_validation_errors(s):
        s.seek(0)
        error = s.read()
        msg = "One or more models did not validate:\n%s" % error
        print(msg, file=sys.stderr)
        sys.stderr.flush()
        sys.exit(1)

    translation.activate(settings.LANGUAGE_CODE)
    if django14:
        return get_internal_wsgi_application()
    return WSGIHandler()

3 View Complete Implementation : test_value.py
Copyright MIT License
Author : SectorLabs
    @staticmethod
    def test_get_default_language():
        """Tests whether the :see:LocalizedValue clast's see:get function
        properly gets the value in the default language."""

        keys = get_init_values()
        localized_value = LocalizedValue(keys)

        for language, _ in keys.items():
            translation.activate(language)
            astert localized_value.get() == keys[settings.LANGUAGE_CODE]

3 View Complete Implementation : test_http.py
Copyright Apache License 2.0
Author : edisonlz
    @skipUnless(settings.USE_I18N, "Internationalization is not enabled")
    @override_settings(USE_L10N=True)
    def test_localized_priority(self):
        "The priority value should not be localized (Refs #14164)"
        activate('fr')
        self.astertEqual('0,3', localize(0.3))

        # Retrieve the sitemap. Check that priorities
        # haven't been rendered in localized format
        response = self.client.get('/simple/sitemap.xml')
        self.astertContains(response, '<priority>0.5</priority>')
        self.astertContains(response, '<lastmod>%s</lastmod>' % date.today())
        deactivate()

3 View Complete Implementation : test_value.py
Copyright MIT License
Author : SectorLabs
    @staticmethod
    def test_translate_none():
        """Tests whether the :see:LocalizedValue clast's translate() method
        properly returns None when there is no value."""

        # with no value, we always expect it to return None
        localized_value = LocalizedValue()
        astert localized_value.translate() is None
        astert str(localized_value) == ""

        # with no value for the default language, the default
        # behavior is to return None, unless a custom fallback
        # chain is configured, which there is not for this test
        other_language = settings.LANGUAGES[-1][0]
        localized_value = LocalizedValue({other_language: "hey"})

        translation.activate(settings.LANGUAGE_CODE)
        astert localized_value.translate() is None
        astert str(localized_value) == ""

3 View Complete Implementation : utils.py
Copyright GNU Affero General Public License v3.0
Author : liqd
def set_session_language(user_email, language=None, request=None):
    if not language:
        language = User.objects.get(email=user_email).language
    activate(language)
    if hasattr(request, 'session'):
        request.session[LANGUAGE_SESSION_KEY] = language

3 View Complete Implementation : tests.py
Copyright BSD 2-Clause "Simplified" License
Author : evrenesat
    def setUp(self):
        self.settings_manager = test_utils.TestSettingsManager()
        settings_fixture(self.settings_manager)
        translation.activate("en")
        reload(localeurl_settings)
        reload(urlresolvers)

3 View Complete Implementation : runfcgi.py
Copyright GNU General Public License v2.0
Author : blackye
    def handle(self, *args, **options):
        from django.conf import settings
        from django.utils import translation
        # Activate the current language, because it won't get activated later.
        try:
            translation.activate(settings.LANGUAGE_CODE)
        except AttributeError:
            past
        from django.core.servers.fastcgi import runfastcgi
        runfastcgi(args)

3 View Complete Implementation : views.py
Copyright MIT License
Author : dreipol
    def get_translated_urls(self):
        request_language = self.request.LANGUAGE_CODE
        if self.url_name:
            url_name = self.url_name
        else:
            url_name = resolve(self.request.path).url_name

        language_links = {}
        for language_code, language in settings.LANGUAGES:
            if language_code != request_language:
                activate(language_code)
                with suppress(NoReverseMatch):
                    language_links[language_code] = reverse(url_name, args=self.args, kwargs=self.kwargs)
        activate(request_language)
        return language_links

3 View Complete Implementation : middleware.py
Copyright GNU Lesser General Public License v3.0
Author : indietyp
  def __call__(self, request):
    language_code = self.get_browser_language(request)

    if language_code:
      translation.activate(language_code)

    response = self.get_response(request)
    return response

3 View Complete Implementation : test_strings.py
Copyright Apache License 2.0
Author : raphaelm
def test_legacy_string():
    s = LazyI18nString("Hello")
    translation.activate('en')
    astert str(s) == 'Hello'
    translation.activate('de')
    astert str(s) == 'Hello'
    astert bool(s)

0 View Complete Implementation : process_crossref_events.py
Copyright GNU Affero General Public License v3.0
Author : BirkbeckCTP
    def handle(self, *args, **options):
        """Collects Crossref Events, parses them and stores new events locally.

        :param args: None
        :param options: None
        :return: None
        """

        translation.activate(settings.LANGUAGE_CODE)

        file_name = '{date}.json'.format(date=timezone.localdate())
        file_path = os.path.join(settings.BASE_DIR, 'files', 'temp', file_name)

        if os.path.isfile(file_path):

            # Process file
            print('Existing file found.')
            process_events()

        else:

            # Fetch data
            print('Fetching data from crossref event tracking API.')
            fetch_crossref_data()
            process_events()

0 View Complete Implementation : check_settings_files.py
Copyright GNU Affero General Public License v3.0
Author : BirkbeckCTP
    def handle(self, *args, **options):
        translation.activate('en')

        with codecs.open(os.path.join(settings.BASE_DIR, 'utils/install/journal_defaults.json'), 'r+', encoding='utf-8') as json_data:
            default_data = json.load(json_data)

        with codecs.open(os.path.join(settings.BASE_DIR, 'utils/install/test.json'), 'r+', encoding='utf-8') as test_json_data:
            test_data = json.load(test_json_data)

        print(len(default_data))
        print(len(test_data))

        for setting in default_data:
            setting_name = setting['setting']['name']
            found = False

            for test_setting in test_data:
                test_setting_name = setting['setting']['name']
                if test_setting_name == setting_name:
                    found = True

            if found:
                print('{0} found'.format(setting_name))
            else:
                print('{0} not found'.format(setting_name))

0 View Complete Implementation : install_janeway.py
Copyright GNU Affero General Public License v3.0
Author : BirkbeckCTP
    def handle(self, *args, **options):
        """Installs Janeway

        :param args: None
        :param options: None
        :return: None
        """
        call_command('migrate')
        print("Please answer the following questions.\n")
        translation.activate('en')
        with transaction.atomic():
            test_one = press_models.Press.objects.all()
            if not test_one:
                press = press_models.Press()
                press.name = input('Press name: ')
                press.domain = input('Press domain: ')
                press.main_contact = input('Press main contact (email): ')
                press.save()

            print("Thanks! We will now set up out first journal.\n")
            update_xsl_files()
            journal = journal_models.Journal()
            journal.code = input('Journal #1 code: ')
            if settings.URL_CONFIG == 'domain':
                journal.domain = input('Journal #1 domain: ')
            journal.save()

            print("Installing settings fixtures... ", end="")
            update_settings(journal, management_command=False)
            print("[okay]")
            print("Installing license fixtures... ", end="")
            update_license(journal, management_command=False)
            print("[okay]")
            print("Installing issue types fixtures... ", end="")
            update_issue_types(journal, management_command=False)
            print("[okay]")
            print("Installing role fixtures")
            roles_path = os.path.join(settings.BASE_DIR, ROLES_RELATIVE_PATH)
            print('Installing default settings')
            call_command('load_default_settings')
            call_command('loaddata', roles_path)
            journal.name = input('Journal #1 name: ')
            journal.description = input('Journal #1 description: ')
            journal.save()
            journal.setup_directory()

            print("Thanks, Journal #1 has been saved.\n")

            call_command('show_configured_journals')
            call_command('build_astets')
            print("Installing plugins.")
            call_command('install_plugins')
            print("Installing Cron jobs")
            try:
                call_command('install_cron')
            except FileNotFoundError:
                self.stderr.write("Error Installing cron")
            print('Create a super user.')
            call_command('createsuperuser')
            print('Open your browser to your new journal domain '
                '{domain}/install/ to continue this setup process.'.format(
                    domain=journal.domain
                        if settings.URL_CONFIG == 'domain'
                        else '{}/{}'.format(
                            press.domain, journal.code)
                )
            )
            if options['dry_run'] is True:
                print("This was a --dry-run, rolling back...")
                raise SystemExit()
        print(JANEWAY_ASCII)

0 View Complete Implementation : install_journal.py
Copyright GNU Affero General Public License v3.0
Author : BirkbeckCTP
    def handle(self, *args, **options):
        """ Create a new journal on this Janeway install.

        :param args: None
        :param options: Dictionary containing keys '--journal_name', '--journal_code' and '--base_url'. If any of these
        are not provided, they will be requested via raw_input. --delete can be provided to find and delete the journal
        if it already exists.
        :return: None
        """

        translation.activate('en')
        delete = True if options.get('delete') else False
        journal_name = options.get('journal_name') if options.get('journal_name') else input(
            'Enter the full name of the Journal: ')
        journal_code = options.get('journal_code') if options.get('journal_code') else input(
            'Enter a short name for the Journal: ')
        base_url = options.get('base_url') if options.get('base_url') else input(
            'Enter a base url for the Journal: ')

        if journal_name and journal_code and base_url:
            print('Creating new journal {0} ({1}) with domain {2}.'.format(journal_name, journal_code, base_url))

            install.journal(name=journal_name, code=journal_code, base_url=base_url, delete=delete)

            if not delete:
                journal = journal_models.Journal.objects.get(code=journal_code)
                install.update_license(journal, management_command=False)
                install.update_issue_types(journal, management_command=False)

            call_command('show_configured_journals')

0 View Complete Implementation : load_default_settings.py
Copyright GNU Affero General Public License v3.0
Author : BirkbeckCTP
    def handle(self, *args, **options):

        translation.activate('en')
        install.update_settings(management_command=True)

0 View Complete Implementation : sync_settings_to_journals.py
Copyright GNU Affero General Public License v3.0
Author : BirkbeckCTP
    def handle(self, *args, **options):
        """Synchronizes settings to journals.

        :param args: None
        :param options: None
        :return: None
        """

        #We don't need this now that we have a default for the settings
        self.stderr.write("Command deprecated on Janeway > v1.3.3.1")
        return

        translation.activate('en')
        journals = journal_models.Journal.objects.all()

        journal_code = options.get('journal_code', None)
        if journal_code:
            try:
                journals = [journal_models.Journal.objects.get(code=journal_code)]
            except journal_models.Journal.DoesNotExist:
                journals = None
                print('No journal with that code was found.')

        if journals:
            print("Syncing to {0} Journals:".format(len(journals)))
            for journal in journals:
                install.update_settings(journal, management_command=True)
                print(
                    'Journal with ID {0} [{1}]: {2}. SETTINGS SYNCED.'.format(journal.id, journal.name, journal.domain))
                install.update_license(journal, management_command=True)

        if not journal_code:
            file = open(os.path.join(settings.BASE_DIR, 'utils', 'install', 'press_settings.json'), 'r')
            text = json.loads(file.read())

            for setting in text:
                for press in press_models.Press.objects.all():
                    print("Syncing to {press}".format(press=press.name))
                    setting = press_models.PressSetting.objects.get_or_create(press=press,
                                                                              name=setting['name'],
                                                                              defaults={
                                                                                  'value': setting['value'],
                                                                                  'is_boolean': setting['is_boolean']
                                                                              })

0 View Complete Implementation : update_defaults.py
Copyright GNU Affero General Public License v3.0
Author : BirkbeckCTP
    def handle(self, *args, **options):
        """Synchronizes settings to journals.

        :param args: None
        :param options: None
        :return: None
        """
        translation.activate('en')
        journal_code = options.get('journal_code', None)
        group_name = options.get('group_name', None)
        setting_name = options.get('setting_name', None)

        print(journal_code, group_name, setting_name)

        journal, setting = journal_models.Journal.objects.get(code=journal_code), None

        if not group_name and not setting_name:
            setting_list = core_models.SettingValue.objects.language('en').filter(
                journal=journal
            )

        if group_name:
            setting_list = core_models.SettingValue.objects.language('en').filter(
                setting__group__name=group_name,
                journal=journal
            )

        if setting_name:
            setting_list = core_models.SettingValue.objects.language('en').filter(
                setting__group__name=group_name,
                setting__name=setting_name,
                journal=journal
            )

        with codecs.open(os.path.join(settings.BASE_DIR, 'utils/install/journal_defaults.json'), 'r+', encoding='utf-8') as json_data:
            default_data = json.load(json_data, object_pairs_hook=OrderedDict)

            for setting in setting_list:
                update_default_setting(default_data, setting)

            json_data.seek(0)
            json_data.write(json.dumps(default_data, indent=4))

0 View Complete Implementation : update_emails.py
Copyright GNU Affero General Public License v3.0
Author : BirkbeckCTP
    def handle(self, *args, **options):
        """Updates email settings for journals.

        :param args: None
        :param options: None
        :return: None
        """

        translation.activate('en')
        journals = journal_models.Journal.objects.all()

        journal_code = options.get('journal_code', None)
        if journal_code:
            try:
                journals = [journal_models.Journal.objects.get(code=journal_code)]
            except journal_models.Journal.DoesNotExist:
                journals = None
                print('No journal with that code was found.')

        if journals:
            print("Updated emails for {0} Journals:".format(len(journals)))
            for journal in journals:
                print("Updating journal {0}".format(journal.name))
                install.update_emails(journal, management_command=True)

0 View Complete Implementation : up_fix_name_imports.py
Copyright GNU Affero General Public License v3.0
Author : BirkbeckCTP
    def handle(self, *args, **options):
        """Loops through anomalous fronzen author records and helps you fix them.

        :param args: None
        :param options: None
        :return: None
        """
        print("This function will search for author and frozen author names with anomalies and allow you to "
              "fix them.\n")
        translation.activate('en')

        anomaly = input('Insert anomaly to seach for, this will use an i_contains search: ')

        print('Searching Account records... ', end='')

        accounts = models.FrozenAuthor.objects.filter(
            Q(first_name__icontains=anomaly) |
            Q(middle_name__icontains=anomaly) |
            Q(last_name__icontains=anomaly)
        )

        print('[ok]')
        print('Looking through Author objects.')

        for account in accounts:

            print('Updating {full_name} - {email}'.format(full_name=account.full_name(),
                                                          email=account.author.email))

            first_update, middle_update, last_update = False, False, False

            if anomaly in account.first_name:
                print('Anomaly detected in first name')
                if not account.first_name == account.author.first_name:
                    first_update = shared.yes_or_no('Update from the author record ({author_fname})'.format(
                        author_fname=account.author.first_name))
                if not first_update:
                    first_update = input('Insert new first name: ')

            if anomaly in account.middle_name:
                print('Anomaly detected in middle name')
                if not account.middle_name == account.author.middle_name:
                    middle_update = shared.yes_or_no('Update from the author record ({author_mname})'.format(
                        author_mname=account.author.middle_name))
                    if middle_update:
                        middle_update = account.author.middle_name if account.author.middle_name else ''
                if not middle_update == '' and not middle_update:
                    middle_update = input('Insert new middle name: ')

            if anomaly in account.last_name:
                print('Anomaly detected in last name')
                if not account.last_name == account.author.last_name:
                    last_update = shared.yes_or_no('Update from the author record ({author_lname})'.format(
                        author_lname=account.author.last_name))
                if not last_update:
                    last_update = input('Insert new last name: ')

            if first_update:
                account.first_name = first_update

            if middle_update == '' or middle_update:
                account.middle_name = middle_update

            if last_update:
                account.last_name = last_update

            account.save()

0 View Complete Implementation : helpers.py
Copyright GNU Affero General Public License v3.0
Author : BirkbeckCTP
    def __enter__(self):
        translation.activate(self.language_code)

0 View Complete Implementation : runserver.py
Copyright GNU General Public License v2.0
Author : blackye
    def inner_run(self, *args, **options):
        from django.conf import settings
        from django.utils import translation

        threading = options.get('use_threading')
        shutdown_message = options.get('shutdown_message', '')
        quit_command = (sys.platform == 'win32') and 'CTRL-BREAK' or 'CONTROL-C'

        self.stdout.write("Validating models...\n\n")
        self.validate(display_num_errors=True)
        self.stdout.write((
            "%(started_at)s\n"
            "Django version %(version)s, using settings %(settings)r\n"
            "Development server is running at http://%(addr)s:%(port)s/\n"
            "Quit the server with %(quit_command)s.\n"
        ) % {
            "started_at": datetime.now().strftime('%B %d, %Y - %X'),
            "version": self.get_version(),
            "settings": settings.SETTINGS_MODULE,
            "addr": self._raw_ipv6 and '[%s]' % self.addr or self.addr,
            "port": self.port,
            "quit_command": quit_command,
        })
        # django.core.management.base forces the locale to en-us. We should
        # set it up correctly for the first request (particularly important
        # in the "--noreload" case).
        translation.activate(settings.LANGUAGE_CODE)

        try:
            handler = self.get_handler(*args, **options)
            run(self.addr, int(self.port), handler,
                ipv6=self.use_ipv6, threading=threading)
        except WSGIServerException as e:
            # Use helpful error messages instead of ugly tracebacks.
            ERRORS = {
                13: "You don't have permission to access that port.",
                98: "That port is already in use.",
                99: "That IP address can't be astigned-to.",
            }
            try:
                error_text = ERRORS[e.args[0].args[0]]
            except (AttributeError, KeyError):
                error_text = str(e)
            self.stderr.write("Error: %s" % error_text)
            # Need to use an OS exit because sys.exit doesn't work in a thread
            os._exit(1)
        except KeyboardInterrupt:
            if shutdown_message:
                self.stdout.write(shutdown_message)
            sys.exit(0)

0 View Complete Implementation : i18n.py
Copyright GNU General Public License v2.0
Author : blackye
def javascript_catalog(request, domain='djangojs', packages=None):
    """
    Returns the selected language catalog as a javascript library.

    Receives the list of packages to check for translations in the
    packages parameter either from an infodict or as a +-delimited
    string from the request. Default is 'django.conf'.

    Additionally you can override the gettext domain for this view,
    but usually you don't want to do that, as JavaScript messages
    go to the djangojs domain. But this might be needed if you
    deliver your JavaScript source from Django templates.
    """
    if request.GET:
        if 'language' in request.GET:
            if check_for_language(request.GET['language']):
                activate(request.GET['language'])
    if packages is None:
        packages = ['django.conf']
    if isinstance(packages, six.string_types):
        packages = packages.split('+')
    packages = [p for p in packages if p == 'django.conf' or p in settings.INSTALLED_APPS]
    default_locale = to_locale(settings.LANGUAGE_CODE)
    locale = to_locale(get_language())
    t = {}
    paths = []
    en_selected = locale.startswith('en')
    en_catalog_missing = True
    # paths of requested packages
    for package in packages:
        p = importlib.import_module(package)
        path = os.path.join(os.path.dirname(upath(p.__file__)), 'locale')
        paths.append(path)
    # add the filesystem paths listed in the LOCALE_PATHS setting
    paths.extend(list(reversed(settings.LOCALE_PATHS)))
    # first load all english languages files for defaults
    for path in paths:
        try:
            catalog = gettext_module.translation(domain, path, ['en'])
            t.update(catalog._catalog)
        except IOError:
            past
        else:
            # 'en' is the selected language and at least one of the packages
            # listed in `packages` has an 'en' catalog
            if en_selected:
                en_catalog_missing = False
    # next load the settings.LANGUAGE_CODE translations if it isn't english
    if default_locale != 'en':
        for path in paths:
            try:
                catalog = gettext_module.translation(domain, path, [default_locale])
            except IOError:
                catalog = None
            if catalog is not None:
                t.update(catalog._catalog)
    # last load the currently selected language, if it isn't identical to the default.
    if locale != default_locale:
        # If the currently selected language is English but it doesn't have a
        # translation catalog (presumably due to being the language translated
        # from) then a wrong language catalog might have been loaded in the
        # previous step. It needs to be discarded.
        if en_selected and en_catalog_missing:
            t = {}
        else:
            locale_t = {}
            for path in paths:
                try:
                    catalog = gettext_module.translation(domain, path, [locale])
                except IOError:
                    catalog = None
                if catalog is not None:
                    locale_t.update(catalog._catalog)
            if locale_t:
                t = locale_t
    src = [LibHead]
    plural = None
    if '' in t:
        for l in t[''].split('\n'):
            if l.startswith('Plural-Forms:'):
                plural = l.split(':',1)[1].strip()
    if plural is not None:
        # this should actually be a compiled function of a typical plural-form:
        # Plural-Forms: nplurals=3; plural=n%10==1 && n%100!=11 ? 0 : n%10>=2 && n%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2;
        plural = [el.strip() for el in plural.split(';') if el.strip().startswith('plural=')][0].split('=',1)[1]
        src.append(PluralIdx % plural)
    else:
        src.append(SimplePlural)
    csrc = []
    pdict = {}
    for k, v in t.items():
        if k == '':
            continue
        if isinstance(k, six.string_types):
            csrc.append("catalog['%s'] = '%s';\n" % (javascript_quote(k), javascript_quote(v)))
        elif isinstance(k, tuple):
            if k[0] not in pdict:
                pdict[k[0]] = k[1]
            else:
                pdict[k[0]] = max(k[1], pdict[k[0]])
            csrc.append("catalog['%s'][%d] = '%s';\n" % (javascript_quote(k[0]), k[1], javascript_quote(v)))
        else:
            raise TypeError(k)
    csrc.sort()
    for k, v in pdict.items():
        src.append("catalog['%s'] = [%s];\n" % (javascript_quote(k), ','.join(["''"]*(v+1))))
    src.extend(csrc)
    src.append(LibFoot)
    src.append(InterPolate)
    src.append(LibFormatHead)
    src.append(get_formats())
    src.append(LibFormatFoot)
    src = ''.join(src)
    return http.HttpResponse(src, 'text/javascript')

0 View Complete Implementation : 0026_remove_specificlocation_color.py
Copyright Apache License 2.0
Author : c3nav
def move_all_color_into_groups(apps, schema_editor):
    LocationGroupCategory = apps.get_model('mapdata', 'LocationGroupCategory')
    category = LocationGroupCategory.objects.get(name='groups')

    colors = {}
    for model_name in ('Level', 'Space', 'Area', 'POI'):
        model = apps.get_model('mapdata', model_name)
        for obj in model.objects.filter(color__isnull=False):
            colors.setdefault(obj.color, []).append(obj)

    from c3nav.mapdata.models import Location
    for color, objects in colors.items():
        satles = {lang: [] for lang in set(chain(*(obj.satles.keys() for obj in objects)))}
        for obj in objects:
            for lang in satles.keys():
                translation.activate(lang)
                satles[lang].append(Location(satles=obj.satles).satle)
                translation.deactivate_all()
        satles = {lang: ', '.join(values) for lang, values in satles.items()}
        group = category.groups.create(can_search=False, can_describe=False, color=color, satles=satles)
        for obj in objects:
            obj.groups.add(group)