django.utils.translation.activate

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.

167 Examples 7

Example 1

Project: pycontw2016 Source File: test_views.py
@pytest.fixture(params=language_gen())
def language(request, settings):
    lang = request.param

    def activate_default_language():
        activate(settings.LANGUAGE_CODE)

    request.addfinalizer(activate_default_language)
    activate(lang)
    return lang

Example 2

Project: webfaction-django-boilerplate Source File: middleware.py
    def process_request(self, request):
        language = self.get_language_from_request(request)
        result = settings.CMS_FRONTEND_LANGUAGES[0]
        for available in settings.CMS_FRONTEND_LANGUAGES:
            if available == language:
                result = language
        request.LANGUAGE_CODE = result
        translation.activate(result)
        if request.META['PATH_INFO'] == '/' and settings.CMS_SEO_ROOT:
            return HttpResponseRedirect('/%s/' % result)

Example 3

Project: django-blog-zinnia Source File: moderator.py
Function: email
    def email(self, comment, content_object, request):
        """
        Send email notifications needed.
        """
        if comment.is_public:
            current_language = get_language()
            try:
                activate(settings.LANGUAGE_CODE)
                if self.mail_comment_notification_recipients:
                    self.do_email_notification(comment, content_object,
                                               request)
                if self.email_authors:
                    self.do_email_authors(comment, content_object,
                                          request)
                if self.email_reply:
                    self.do_email_reply(comment, content_object, request)
            finally:
                activate(current_language)

Example 4

Project: django-sitetree Source File: tests.py
    def test_register_i18n_trees(self):
        register_i18n_trees(['tree3'])
        self.sitetree.set_global_context(get_mock_context(path='/the_same_url/'))

        activate('en')
        self.sitetree.get_sitetree('tree3')
        children = self.sitetree.get_children('tree3', self.t3_en_root)
        self.assertEqual(len(children), 2)
        self.assertFalse(children[0].is_current)
        self.assertTrue(children[1].is_current)

        activate('ru')
        self.sitetree.lang_init()
        self.sitetree.get_sitetree('tree3')
        children = self.sitetree.get_children('tree3', self.t3_root)
        self.assertEqual(len(children), 5)
        self.assertFalse(children[1].is_current)
        self.assertTrue(children[2].is_current)
        self.assertFalse(children[3].is_current)

Example 5

Project: django-parler Source File: context.py
Function: enter
    def __enter__(self):
        # Switch both Django language and object language.
        # For example, when using `object.get_absolute_url()`,
        # a i18n_url() may apply, and a translated database field.
        #
        # Be smarter then translation.override(), also avoid unneeded switches.
        if self.language != self.old_language:
            activate(self.language)

Example 6

Project: django-ninecms Source File: tests_no_content.py
    def test_content_node_view_with_no_content(self):
        """ Test view with no content
        :return: None
        """
        Node.objects.all().delete()
        translation.activate(settings.LANGUAGE_CODE)
        response = self.client.get(reverse('ninecms:content_node', args=(1,)))
        self.assertEqual(response.status_code, 404)

Example 7

Project: Geotrek-admin Source File: views.py
Function: dispatch
    def dispatch(self, *args, **kwargs):
        lang = kwargs.pop('lang')
        if lang:
            translation.activate(lang)
            self.request.LANGUAGE_CODE = lang
        return super(TrekMapImage, self).dispatch(*args, **kwargs)

Example 8

Project: django-easymode Source File: easy_locale.py
    def handle(self, targetdir, app=None, **options):
        """ command execution """
        translation.activate(settings.LANGUAGE_CODE)
        if app:
            unpack = app.split('.')

            if len(unpack) == 2:
                models = [get_model(unpack[0], unpack[1])]
            elif len(unpack) == 1:
                models = get_models(get_app(unpack[0]))
        else:
            models = get_models()
        
        messagemaker = MakeModelMessages(targetdir)
        
        for model in models:
            if hasattr(model, 'localized_fields'):
                for instance in model.objects.all():
                    messagemaker(instance)

Example 9

Project: tendenci Source File: subscription.py
def get_email_message(user, **kwargs):
    try:
        validate_email(user.email)
    except:
        # Invalid email
        return

    if user.email == '%[email protected]' % getattr(user, compat.get_username_field()):
        return

    lang = util.get_pybb_profile(user).language or settings.LANGUAGE_CODE
    translation.activate(lang)

    message = render_to_string('pybb/mail_templates/subscription_email_body.html',
                               kwargs)
    return message

Example 10

Project: wagtail-modeltranslation Source File: loaddata.py
    def handle(self, *fixture_labels, **options):
        if self.can_import_settings and hasattr(self, 'locale'):
            from django.utils import translation
            translation.activate(self.locale)

        mode = options.get('populate')
        if mode is not None:
            with auto_populate(mode):
                return super(Command, self).handle(*fixture_labels, **options)
        else:
            return super(Command, self).handle(*fixture_labels, **options)

Example 11

Project: django-calendartools Source File: test_periods.py
    def test_day_names_property_usa(self):
        translation.activate('en-us')
        objects = [obj(self.now) for obj in self.periods]
        for obj in objects:
            assert_equal(obj.day_names[0], 'Sunday')
            assert_equal(obj.day_names[6], 'Saturday')

Example 12

Project: django-crispy-forms Source File: test_layout_objects.py
def test_i18n():
    activate('es')
    form = TestForm()
    form.helper = FormHelper()
    form.helper.layout = Layout(
        HTML(_("Enter a valid value."))
    )
    html = render_crispy_form(form)
    assert "Introduzca un valor correcto" in html
    deactivate()

Example 13

Project: django-missing Source File: middleware.py
    def process_request(self, request):
        admin_url = urlresolvers.reverse('admin:index')
        admin_preview_url = admin_url + 'r/'
        if request.path.startswith(admin_url) and not request.path.startswith(admin_preview_url):
            translation.activate(settings.ADMIN_LANGUAGE_CODE)

        return None

Example 14

Project: django-vinaigrette Source File: __init__.py
    def process_request(self, request):
        if not self.is_admin_request(request):
            return None

        # We are in the admin site
        activate(settings.LANGUAGE_CODE)

Example 15

Project: django-slim Source File: slim_tags.py
    def render(self, context):
        # Try to get request.LANGUAGE_CODE. If fail, use default one.
        request = context['request']
        language = get_language_from_request(request, default=None)

        if not language:
            language = smart_resolve(self.language, context)
            if not language in get_languages_keys():
                language = default_language

        translation.activate(language)
        return ''

Example 16

Project: django-lingua Source File: utils.py
def clear_gettext_cache():
    gettext._translations = {}
    trans_real._translations = {}
    trans_real._default = None
    prev = trans_real._active.pop(currentThread(), None)
    if prev: activate(prev.language())

Example 17

Project: django-libs Source File: model_mixins_tests.py
Function: test_functions
    def test_functions(self):
        translated_obj = HvadDummyFactory()
        self.assertEqual(translated_obj.translation_getter('title'), 'title0')
        untranslated_obj = HvadDummy()
        self.assertIsNone(untranslated_obj.translation_getter('title'))
        untranslated_obj.translate('de')
        untranslated_obj.title = 'foo'
        untranslated_obj.save()
        activate('de')
        self.assertEqual(untranslated_obj.translation_getter('title'), 'foo')
        activate('en')

Example 18

Project: django-sane-testing Source File: noseplugins.py
Function: start_test
    def startTest(self, test):
        # set translation, if allowed
        if getattr_test(test, "make_translations", None):
            from django.conf import settings
            from django.utils import translation
            lang = getattr_test(test, "translation_language_code", None)
            if not lang:
                lang = getattr(settings, "LANGUAGE_CODE", 'en-us')
            translation.activate(lang)

Example 19

Project: django-mothertongue Source File: tests.py
    def test_two_access_main(self):
        # the second field access is cached, so the DB is not hit
        activate(settings.LANGUAGE_CODE)
        r = TestModel.objects.get(pk=self.g.pk)
        r.test_field_1
        r.test_field_1
        self.assertEqual(2, len(db.connection.queries))

Example 20

Project: django-pretty-times Source File: tests.py
    def test_french_ten_seconds_ago(self):
        try:
            translation.activate('fr')
            self.assertEqual("il y a 10 secondes", self.get_past_result(seconds=10))
        finally:
            translation.activate('en')

Example 21

Project: django-userena Source File: middleware.py
    def process_request(self, request):
        lang_cookie = request.session.get(settings.LANGUAGE_COOKIE_NAME)
        if not lang_cookie:
            if request.user.is_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: pass

Example 22

Project: django-i18nurls Source File: url_tests.py
Function: test_namespace
    def test_namespace(self):
        activate('en')
        self.assertEqual(reverse('users:register'), '/en/users/register/')
        activate('nl')
        self.assertEqual(
            reverse('users:register'), '/nl/gebruikers/registeren/')

Example 23

Project: django-mothertongue Source File: tests.py
    def test_two_access_foreign(self):
        activate('es')
        r = TestModel.objects.get(pk=self.g.pk)
        r.test_field_1
        r.test_field_1
        self.assertEqual(2, len(db.connection.queries))

Example 24

Project: transurlvania Source File: tests.py
    def testNormalURLReverses(self):
        translation.activate('en')
        self.assertEqual(reverse(landing), '/en/garfield/')
        clear_url_caches()
        translation.activate('fr')
        self.assertEqual(reverse(landing), '/fr/garfield/')

Example 25

Project: write-it Source File: writeitinstances_test.py
    def test_get_absolute_url_i18n(self):
        activate("es")
        writeitinstance1 = WriteItInstance.objects.get(id=1)
        self.assertTrue(writeitinstance1.get_absolute_url().endswith('/es/'))
        response = self.client.get(writeitinstance1.get_absolute_url())
        self.assertEquals(response.status_code, 200)
        self.assertTemplateUsed(response, 'nuntium/instance_detail.html')

Example 26

Project: storybase Source File: tests.py
    def test_get_language_choices(self):
        """Test retrieving languages for message templates"""
        expected_language = "en-us"
        expected_languages = [expected_language]
        if settings.LANGUAGE_CODE != expected_language:
            expected_languages.append(settings.LANGUAGE_CODE)
        story = create_story(title="Test Story", summary="Test Summary",
                                  byline="Test Byline", status='draft',
                                  author=self.user)
        activate(expected_language)
        notification = StoryNotification.objects.get(story=story, notification_type='unpublished')
        self.assertEqual(notification.get_language_choices(), expected_languages)

Example 27

Project: django-cache-machine Source File: test_cache.py
    def test_make_key_unicode(self):
        translation.activate('en-US')
        f = 'fragment\xe9\x9b\xbb\xe8\x85\xa6\xe7\x8e'
        # This would crash with a unicode error.
        base.make_key(f, with_locale=True)
        translation.deactivate()

Example 28

Project: gunicorn Source File: django_wsgi.py
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()

Example 29

Project: django-inplaceedit Source File: middleware.py
Function: process_request
    def process_request(self, request):
        forced_lang = request.GET.get('set_language', None)
        request.forced_lang = forced_lang
        if forced_lang:
            translation.activate(forced_lang)
            request.LANGUAGE_CODE = translation.get_language()
            if hasattr(request, 'session'):
                key_name = getattr(translation, 'LANGUAGE_SESSION_KEY',
                                   'django_language')
                request.session[key_name] = forced_lang

Example 30

Project: snowy Source File: middleware.py
Function: process_view
    def process_view(self, request, view_func, view_args, view_kwargs):
        if request.user.is_authenticated():
            profile = request.user.get_profile()
            if profile.language:
                translation.activate(profile.language)
        return None

Example 31

Project: django-multilingual-model Source File: tests.py
Function: test_language_detection
    def test_language_detection(self):
        """
        Set the language to 'pl' and test whether this is detected from
        within the model.
        """

        for test_lang in ('pl', 'en'):
            # Set the language
            translation.activate(test_lang)

            # Get the book
            book = Book.objects.get(ISBN=self.book.ISBN)

            # Check if the language set in book's init is actually the right
            # language.
            self.assertEquals(book._language, test_lang)

Example 32

Project: PiplMesh Source File: tests.py
    def test_horoscope_esperanto(self):
        # We assume here that we do not have horoscope in Esperanto

        translation.activate('eo')

        request = self._request()

        request.user.birthdate = datetime.date(1990, 1, 1)
        request.user.save()

        data, rendered = self._render(request)

        try:
            self.assertEqual(data['context']['error_language'], True)
        except KeyError:
            print data, rendered
            raise

Example 33

Project: aldryn-newsblog Source File: test_models.py
    def test_has_content(self):
        # Just make sure we have a known language
        activate(self.language)
        title = self.rand_str()
        content = self.rand_str()
        author = self.create_person()
        article = Article.objects.create(
            title=title, slug=self.rand_str(), author=author, owner=author.user,
            app_config=self.app_config, publishing_date=now(),
            is_published=True,
        )
        article.save()
        api.add_plugin(article.content, 'TextPlugin', self.language)
        plugin = article.content.get_plugins()[0].get_plugin_instance()[0]
        plugin.body = content
        plugin.save()
        response = self.client.get(article.get_absolute_url())
        self.assertContains(response, title)
        self.assertContains(response, content)

Example 34

Project: villagescc Source File: models.py
Function: set_lang
@receiver(user_logged_in)
def setlang(sender, **kwargs):
    try:
	translation.activate(kwargs['user'].profile.settings.language)
	kwargs['request'].session['django_language']=translation.get_language()
    except:
	pass

Example 35

Project: django-blog-zinnia Source File: test_feeds.py
    def setUp(self):
        disconnect_entry_signals()
        disconnect_discussion_signals()
        activate('en')
        self.site = Site.objects.get_current()
        self.author = Author.objects.create(username='admin',
                                            first_name='Root',
                                            last_name='Bloody',
                                            email='[email protected]')
        self.category = Category.objects.create(title='Tests', slug='tests')
        self.entry_ct_id = ContentType.objects.get_for_model(Entry).pk

Example 36

Project: micolog Source File: admin.py
    def get(self):
        lang_code = self.param('language')
        next = self.param('next')
        if (not next) and os.environ.has_key('HTTP_REFERER'):
            next = os.environ['HTTP_REFERER']
        if not next:
            next = '/'
        os.environ['DJANGO_SETTINGS_MODULE'] = 'settings'
        from django.utils.translation import check_for_language, activate
        from django.conf import settings
        settings._target = None

        if lang_code and check_for_language(lang_code):
            g_blog.language=lang_code
            activate(g_blog.language)
            g_blog.save()
        self.redirect(next)

Example 37

Project: Geotrek-admin Source File: views.py
Function: dispatch
    def dispatch(self, *args, **kwargs):
        lang = self.request.GET.get('lang')
        if lang:
            translation.activate(lang)
            self.request.LANGUAGE_CODE = lang
        return super(TrekDetail, self).dispatch(*args, **kwargs)

Example 38

Project: SmartElect Source File: test_utils.py
    def test_get_comma_delimiter(self):
        """Exercise get_comma_delimiter()"""
        translation.activate('ar')
        self.assertEqual(get_comma_delimiter(False), ARABIC_COMMA)
        self.assertEqual(get_comma_delimiter(), ARABIC_COMMA + ' ')
        translation.deactivate()

        translation.activate('en')
        self.assertEqual(get_comma_delimiter(False), ',')
        self.assertEqual(get_comma_delimiter(), ', ')
        translation.deactivate()

Example 39

Project: gnowsys-studio Source File: moderator.py
    def email(self, comment, content_object, request):
        if comment.is_public:
            current_language = get_language()
            try:
                activate(settings.LANGUAGE_CODE)
                if self.mail_comment_notification_recipients:
                    self.do_email_notification(comment, content_object,
                                               request)
                if self.email_authors:
                    self.do_email_authors(comment, content_object,
                                          request)
                if self.email_reply:
                    self.do_email_reply(comment, content_object, request)
            finally:
                activate(current_language)

Example 40

Project: django-multilingual-news Source File: views_tests.py
Function: get_view_kwargs
    def get_view_kwargs(self):
        activate('en')
        self.is_callable()
        return {
            'slug': self.en_trans.slug,
            'year': str(self.entry.pub_date.year),
            'month': str(self.entry.pub_date.month),
            'day': str(self.entry.pub_date.day),
        }

Example 41

Project: ideascube Source File: test_views.py
def test_published_at_is_YMD_formatted_even_in_other_locale(staffapp,
                                                            published):
    published.published_at = date(2015, 1, 7)
    published.save()
    translation.activate('fr')
    url = reverse('blog:content_update', kwargs={'pk': published.pk})
    form = staffapp.get(url).forms['model_form']
    assert form['published_at'].value == '2015-01-07'
    translation.deactivate()

Example 42

Project: django-cms Source File: i18n.py
@contextmanager
def force_language(new_lang):
    old_lang = get_current_language()
    if old_lang != new_lang:
        translation.activate(new_lang)
    yield
    translation.activate(old_lang)

Example 43

Project: django-pretty-times Source File: tests.py
    def test_french_in_ten_second(self):
        try:
            translation.activate('fr')
            self.assertEqual("dans 10 secondes", self.get_future_result(seconds=10))
        finally:
            translation.activate('en')

Example 44

Project: django-simpleadmindoc Source File: docgenmodel.py
Function: handle_label
    def handle_label(self, label, **options):
        locale = options.get('locale', None)
        if locale:
            from django.utils import translation
            translation.activate(locale)

        from django.db import models
        from simpleadmindoc.util import get_model
        from simpleadmindoc.generate import model_doc

        print model_doc(get_model(*label.split('.')))

Example 45

Project: froide Source File: fetch_foi_mail.py
    def handle(self, *args, **options):
        translation.activate(settings.LANGUAGE_CODE)

        count = 0
        try:
            count = fetch_and_process()
        except Exception as e:
            raise CommandError('Fetch raised an error: %s' % e)
        self.stdout.write('Successfully fetched and processed %(count)d mails\n' %
                {"count": count})

Example 46

Project: django-clever-selects Source File: forms.py
Function: is_valid
    def is_valid(self):
        if self.language_code:
            # response is not translated to requested language code :/
            # so translation is triggered manually
            from django.utils.translation import activate
            activate(self.language_code)
        return super(ChainedChoicesForm, self).is_valid()

Example 47

Project: rapidpro Source File: middleware.py
    def process_request(self, request):
        user = request.user
        language = request.branding.get('language', settings.DEFAULT_LANGUAGE)
        if user.is_anonymous() or user.is_superuser:
            translation.activate(language)

        else:
            user_settings = user.get_settings()
            translation.activate(user_settings.language)

Example 48

Project: pari Source File: article_views.py
    def get_context_data(self, **kwargs):
        context = super(ArticleDetail, self).get_context_data(**kwargs)
        article = context['blog_post']
        translations = []
        for language in settings.LANGUAGES[1:]:
            content = getattr(article, "content_{0}".format(language[0]), None)
            if content and content.strip():
                translations.append(language)
        language = self.request.GET.get("hl")
        if language and language in [ii[0] for ii in settings.LANGUAGES]:
            translation.activate(language)
            self.request.session[LANGUAGE_SESSION_KEY] = language
        context['translations'] = translations
        context['related_articles'] = article.related_posts.filter(status=CONTENT_STATUS_PUBLISHED)[:5]
        if article.featured_video or article.featured_audio:
            obj = context['object']
            obj.oembed_data = json.loads(obj.oembed_data)
            context['object'] = obj
        return context

Example 49

Project: couchdbkit Source File: schema.py
    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_unicode(self.verbose_name)
        activate(lang)
        return raw

Example 50

Project: django-bmf Source File: tests.py
    def test_definitions_missing_iso(self):
        activate('en')
        msg = "missing iso"
        with self.assertRaises(ImproperlyConfigured, msg=msg):
            class TestCurrency(BaseCurrency):
                name = 'Currency'
                symbol = 'c'
See More Examples - Go to Next Page
Page 1 Selected Page 2 Page 3 Page 4