예제 #1
0
파일: i18n.py 프로젝트: Aliced3645/django
 def get_language_info(self, language):
     # ``language`` is either a language code string or a sequence
     # with the language code as its first item
     if len(language[0]) > 1:
         return translation.get_language_info(language[0])
     else:
         return translation.get_language_info(str(language))
    def handle(self, *args, **options):
        if args:
            raise CommandError("Command doesn't accept any arguments")

        site = options['site']
        host = options['host']
        from_lang = options['from']
        to_lang = options['to']

        if not from_lang:
            raise CommandError("Provide a --from=.. language to redirect for")
        if not host:
            host = Site.objects.get_current().domain

        if '://' not in host:
            host = "http://{0}".format(host)

        from_name = get_language_info(from_lang)['name']
        to_name = get_language_info(to_lang)['name']

        with translation.override(from_lang):
            qs = (UrlNode.objects
                  .parent_site(site)
                  .non_polymorphic()
                  .translated(to_lang)
                  .order_by('translations___cached_url'))
            if not qs:
                raise CommandError("No URLs found for site {0} in {1}".format(site, from_name))

            self.stdout.write('# Redirecting all translated {0} URLs to the {1} site\n'.format(from_name, to_name))
            self.stdout.write("# Generated using {0}".format(" ".join(sys.argv)))

            for page in qs:
                from_url = page.default_url
                with switch_language(page, to_lang):
                    to_url = page.get_absolute_url()

                if from_url == to_url:
                    continue

                if from_url.endswith('/'):
                    from_regexp = from_url.rstrip('/')
                    from_rule = "~ ^{0}(/|$)".format(from_regexp)
                else:
                    from_regexp = from_url
                    from_rule = "= {0}".format(from_regexp)

                if page.plugin.urls:
                    self.stdout.write("location {0} {{ rewrite ^{1}(.*)$  {2}{3}$1; }}\n".format(
                        from_rule, from_regexp, host, to_url.rstrip('/')
                    ))
                else:
                    self.stdout.write("location {0} {{ return 301 {1}{2}; }}\n".format(
                        from_rule, host, to_url
                    ))

            # Final redirect for all identical URLs
            self.stdout.write("\n# Redirect all remaining and identical URls:\n")
            self.stdout.write("location / {{ rewrite ^/(.*)$  {0}/$1 permanent; }}\n".format(host))
예제 #3
0
파일: views.py 프로젝트: hrohilft/need
def langchoice(request):
	referer = request.META["HTTP_REFERER"]
	ar = get_language_info('ar')
	#fa = get_language_info('fa')
	de = get_language_info('de')
	en = get_language_info('en')
	languages = [ar, de, en] #fa,
	return render(request, 'need/langchoice.html', {'languages': languages, 'referer': referer})
예제 #4
0
파일: views.py 프로젝트: caujka/TripJournal
def settings(request):
    args={}
    args.update(csrf(request))
    if request.user.is_authenticated():    
        args['user']=request.user
    current_language=get_language_info(request.LANGUAGE_CODE)
    args['current_language']=current_language
    another_language=[]
    for lang in TripJournal_settings.LANGUAGES:
        if lang[0] != request.LANGUAGE_CODE:
            another_language.append(get_language_info(lang[0]))
    args['another_language']=another_language
    return render(request, "settings.html", args)
예제 #5
0
파일: dateparsing.py 프로젝트: amcat/amcat
def _get_language_aliases(language: 'dateparser.languages.Locale') -> Iterable[str]:
    yield language.info['name']
    yield language.shortname
    try:
        yield get_language_info(language.shortname)['name_local']
    except KeyError:
        pass
예제 #6
0
파일: utils.py 프로젝트: goetzk/tendenci
def get_languages_with_local_name():
    """
    Get a list of tuples of available languages with local name.
    """
    return [(ll['code'], '%s (%s)' % (ll['name_local'], ll['code'])) for ll in
            [translation.get_language_info(l[0])
             for l in settings.LANGUAGES]]
예제 #7
0
파일: views.py 프로젝트: nextcloud/appstore
    def get_queryset(self):
        order_by = self.request.GET.get('order_by', 'rating_overall')
        ordering = self.request.GET.get('ordering', 'desc')
        is_featured = self.request.GET.get('is_featured', False)
        maintainer = self.request.GET.get('maintainer', False)
        sort_columns = []

        allowed_order_by = {'name', 'last_release', 'rating_overall',
                            'rating_recent'}
        if order_by in allowed_order_by:
            if order_by == 'name':
                order_by = 'translations__name'
            if ordering == 'desc':
                sort_columns.append('-' + order_by)
            else:
                sort_columns.append(order_by)

        lang = get_language_info(get_language())['code']
        category_id = self.kwargs['id']
        queryset = App.objects.search(self.search_terms, lang).order_by(
            *sort_columns).filter(releases__gt=0)
        if maintainer:
            try:
                user = User.objects.get_by_natural_key(maintainer)
                queryset = queryset.filter(Q(owner=user) |
                                           Q(co_maintainers=user))
            except ObjectDoesNotExist:
                return queryset.none()
        if category_id:
            queryset = queryset.filter(categories__id=category_id)
        if is_featured == "true":
            queryset = queryset.filter(is_featured=True)
        return queryset.prefetch_related('screenshots', 'translations')
예제 #8
0
파일: querysets.py 프로젝트: hdknr/djres
 def get_lang(self, name):
     info = translation.get_language_info(name)
     lang, created = self.get_or_create(code=info['code'])
     if created:
         map(lambda (k, v): setattr(lang, k, v), info.items())
         lang.save()
     return lang
예제 #9
0
    def __init__(self, *args, **kwargs):
        super(UserSettingsForm, self).__init__(*args, **kwargs)

        # Languages
        languages = [(k, "%s (%s)"
                      % (translation.get_language_info(k)['name_local'], k))
                      for k, v in settings.LANGUAGES]
        self.fields['language'].choices = languages

        # Timezones
        d = datetime(datetime.today().year, 1, 1)
        timezones = []
        for tz in pytz.common_timezones:
            try:
                utc_offset = pytz.timezone(tz).localize(d).strftime('%z')
                utc_offset = " (UTC %s:%s)" % (utc_offset[:3], utc_offset[3:])
            except:
                utc_offset = ""

            if tz != "UTC":
                tz_name = "%s%s" % (tz, utc_offset)
            else:
                tz_name = tz
            timezones.append((tz, tz_name))

        self.fields['timezone'].choices = timezones
예제 #10
0
def getLanguageOptions():
    languageOptions = []
    languages = ('en', 'de', 'es', 'nl', 'fr', 'pt', 'ru', 'sv')
    for language in languages:
        option = {'code': language, 'name': get_language_info(language)['name_local']}
        languageOptions.append(option)
    return languageOptions
예제 #11
0
 def render(self, name, value, attrs=None):
     output = super(TrumbowygWidget, self).render(name, value, attrs)
     script = u'''
         <script>
             $("#id_%s").trumbowyg({
                 lang: "%s",
                 semantic: true,
                 resetCss: true,
                 autogrow: true,
                 btns: [
                     "formatting",
                     "|", $.trumbowyg.btnsGrps.design,
                     "|", "link",
                     "|", "upload", "video",
                     "|", $.trumbowyg.btnsGrps.justify,
                     "|", $.trumbowyg.btnsGrps.lists,
                     "|", "horizontalRule",
                     "|", "viewHTML"
                 ],
                 uploadUrl: "%s"
             });
         </script>
     ''' % (name, get_language_info(get_language())['code'], reverse('trumbowyg_upload_image'))
     output += mark_safe(script)
     return output
예제 #12
0
    def render_change_form(self, request, context, add=False, change=False,
                           form_url='', obj=None):
        lang_code = self._language(request)
        lang = get_language_info(lang_code)['name_local']
        available_languages = [] if obj is None else obj.get_available_languages()

        context.update({
            'title': '%s (%s)' % (context['title'], lang),
            'current_is_translated': lang_code in available_languages,
            'allow_deletion': len(available_languages) > 1,
            'language_tabs': self.get_language_tabs(obj, request, available_languages),
            'base_template': self.get_change_form_base_template(),
        })

        # Ensure form action url carries over tab language
        qs_language = request.GET.get('language')
        if qs_language:
            form_url = urlparse(form_url or request.get_full_path())
            query = QueryDict(form_url.query, mutable=True)
            if 'language' not in query:
                query['language'] = qs_language
            form_url = form_url._replace(query=query.urlencode()).geturl()

        return super(TranslatableAdmin, self).render_change_form(request,
                                                                  context,
                                                                  add, change,
                                                                  form_url, obj)
예제 #13
0
파일: views.py 프로젝트: bigali/alfanous
def results(request):

    response = RAWoutput.do( request.GET )

    # language information
    language = translation.get_language_from_request(request)
    language_info = get_language_info(language)

    #print  language ,language_info['name'], language_info['name_local'], language_info['bidi']
     

    translation.activate(language)
    request.LANGUAGE_CODE = translation.get_language()
    

    return render_to_response('wui.html', 
                              {
                                "bidi": "rtl" if language_info['bidi'] 
                                              else "ltr",
                                "language_local_name": language_info['name_local'],
                                "align": "right" if language_info['bidi'] 
                                              else "left",
                                "align_inverse": "left" if language_info['bidi'] 
                                              else "right",
                                "image_extension": "_ar" if language_info['bidi'] 
                                              else "_en"
                                
                               }
                              )
예제 #14
0
 def test_language_name_local(self):
     """LANGUAGE_NAME_LOCAL should be in context"""
     self.assertTrue("LANGUAGE_NAME_LOCAL" in self.result)
     code = translation.get_language()
     code = "en" if code == "en-us" else code
     language = translation.get_language_info(code)
     self.assertEqual(self.result["LANGUAGE_NAME_LOCAL"], language["name_local"])
예제 #15
0
def get_language_choices(shop=None):
    """
    Returns a list of the available language choices, e.g.:
        [("en", "English", "English"])

    If shot is passed, the languages will be filtered by those
    enabled for the shop.

    :rtype iterable[(str, str, str)]
    """
    available_languages = []
    languages = []

    if shop:
        available_languages = configuration.get(shop, FRONT_AVAILABLE_LANGUAGES_CONFIG_KEY)
        if available_languages:
            available_languages = available_languages.split(",")

    for code, name in settings.LANGUAGES:
        if available_languages and code not in available_languages:
            continue

        lang_info = get_language_info(code)
        name_in_current_lang = ugettext(name)
        local_name = lang_info["name_local"]
        languages.append((code, name_in_current_lang, local_name))
    return languages
예제 #16
0
 def test_language_name_local(self):
     '''LANGUAGE_NAME_LOCAL should be in context'''
     result = self.process_request()
     self.assertIn('LANGUAGE_NAME_LOCAL', result)
     code = translation.get_language()
     code = 'en' if code == 'en-us' else code
     language = translation.get_language_info(code)
     self.assertEqual(result['LANGUAGE_NAME_LOCAL'], language['name_local'])
예제 #17
0
파일: forms.py 프로젝트: clone1612/appstore
def get_languages_local(language=None):
    if language:
        languages = [language]
    else:
        languages = [l[0] for l in settings.LANGUAGES]

    return [(li['code'], li['name_local'])
            for li in [get_language_info(l) for l in languages]]
예제 #18
0
 def test_language_name(self):
     '''LANGUAGE_NAME should be in context'''
     result = self.process_request()
     self.assertTrue('LANGUAGE_NAME' in result)
     code = translation.get_language()
     code = 'en' if code == 'en-us' else code
     language = translation.get_language_info(code)
     self.assertEqual(result['LANGUAGE_NAME'], language['name'])
예제 #19
0
def get_language(request):
    """Given a request, check the GET params and then the session to find
    language info specified in 2 char ISO code form, and then make sure it's
    valid, and return a tuple in the format of django's get_language_info.
    Nonexistent languages raise KeyError."""
    lang = request.GET.get("lang",
                           request.session.get('django_language', 'en'))
    return get_language_info(lang)
예제 #20
0
 def get_language_display_name(code, desc):
     try:
         desc = translation.get_language_info(code)['name_local']
     except KeyError:
         # If a language is not defined in django.conf.locale.LANG_INFO
         # get_language_info raises KeyError
         pass
     return "%s (%s)" % (desc, code)
예제 #21
0
def my_get_language_info(lang_code):
  try:
    return translation.get_language_info(lang_code)
  except KeyError:
    if lang_code in settings.EXTRA_LANGUAGES:
      return settings.EXTRA_LANGUAGES[lang_code]
    else:
      raise KeyError(ERROR_MESSAGE % lang_code)
예제 #22
0
파일: general.py 프로젝트: suutari/shoop
def get_shop_language_choices(context):
    languages = []
    for code, name in settings.LANGUAGES:
        lang_info = get_language_info(code)
        name_in_current_lang = ugettext(name)
        local_name = lang_info["name_local"]
        languages.append((code, name_in_current_lang, local_name))
    return languages
예제 #23
0
def get_shop_language_choices(context):
    request = context["request"]
    languages = []
    for code, name in configuration.get(request.shop, "languages", settings.LANGUAGES):
        lang_info = get_language_info(code)
        name_in_current_lang = ugettext(name)
        local_name = lang_info["name_local"]
        languages.append((code, name_in_current_lang, local_name))
    return languages
예제 #24
0
def fix_languages(node):
    if (isinstance(node, Element) and
       node.tagName == 'translation' and node.hasAttribute('lang')):
        iso_lang = node.getAttribute('lang')
        local_lang = get_language_info(iso_lang)['name_local']
        node.setAttribute('lang', local_lang)
    else:
        for child in node.childNodes:
            fix_languages(child)
예제 #25
0
def slim_language_local_name(lang_code):
    """Localised language name.

    :param str lang_code:
    :return str:
    """
    try:
        return translation.get_language_info(lang_code)['name_local']
    except:
        return lang_code
예제 #26
0
 def languages(self):
     '''
     returns a list of language info dicts for templates
     '''
     lang_codes = self._languages()
     langs = []
     for lang in self.lang_choices:
         if lang[0] in lang_codes:
             langs.append(get_language_info(lang[0]))
     return langs
예제 #27
0
 def _media(self):
     lang = get_language_info(translation.get_language())
     css = {
         'all': ('simple_review/vendor/raty/jquery.raty.css',)
     }
     if lang['bidi']:
         css['all'] = css['all'] + ('simple_review/raty.rtl.css',)
     return forms.Media(css=css,
                        js=('simple_review/vendor/raty/jquery.raty.js',
                            'simple_review/raty_init.js'))
예제 #28
0
def get_native_language_name(lang_code):
    try:
        return get_language_info(lang_code)['name_local']
    except KeyError:
        pass
    try:
        return NATIVE_LANGUAGE_NAMES[lang_code]
    except KeyError:
        raise KeyError(u'Please add an entry for {} to '
                       u'kobo.static_lists.NATIVE_LANGUAGE_NAMES and try '
                       u'again.'.format(lang_code))
예제 #29
0
    def __init__(self, *args, **kwargs):
        super(UserSettingsForm, self).__init__(*args, **kwargs)

        # Languages
        languages = [(k, "%s (%s)"
                      % (translation.get_language_info(k)['name_local'], k))
                      for k, v in settings.LANGUAGES]
        self.fields['language'].choices = languages

        # Timezones
        timezones = [(tz, tz) for tz in pytz.common_timezones]
        self.fields['timezone'].choices = timezones
예제 #30
0
파일: views.py 프로젝트: rezometz/paiji2
def confirm_language(request, code):
    if request.method == "POST":
        return set_language(request)

    if check_for_language(code) and code in dict(settings.LANGUAGES):
        new_language = get_language_info(code)
    else:
        return redirect(settings.REDIRECT_URL)

    next_page = request.GET.get("next", settings.REDIRECT_URL)

    return render(request, "paiji2/confirm_language.html", context={"new_language": new_language, "next": next_page})
예제 #31
0
def language_name(lang_code):
    return translation.get_language_info(lang_code)["name"]
예제 #32
0
 def handle(self, *args, **kwargs):
     for tag, name in settings.LANGUAGES:
         info = get_language_info(tag)
         Language.objects.get_or_create(ietf_tag=tag, name=name)
예제 #33
0
파일: utils.py 프로젝트: slonidet/volunteer
def get_language_bidi(lang):
    """
    Check if a language is bi-directional.
    """
    lang_info = get_language_info(lang)
    return lang_info['bidi']
예제 #34
0
def language_name_translated(lang_code):
    english_name = translation.get_language_info(lang_code)["name"]
    return translation.gettext(english_name)
예제 #35
0
 def sorted_chunks(self):
     bidi = get_language_info(get_language())['bidi']
     return sorted(filter(partial(filter_by_bidi, bidi), self.bundle),
                   key=lambda x: x['name'].split('.')[-1])
예제 #36
0
from django.db import models
from django.utils import timezone
from django.utils.translation import get_language_info
from django.utils.translation import ugettext_lazy as _

LANGUAGES = (
    ("en", _(get_language_info("en")["name"])),
    ("ru", _(get_language_info("ru")["name"])),
    ("kk", _(get_language_info("kk")["name"])),
)

COURSE_LANGUAGES = (
    ("en", _("English")),
    ("ru", _("Russian")),
    ("kk", _("Kazakh")),
)


# ABSTRACT CLASSES
class MyDateTimeField(models.DateTimeField):
    def pre_save(self, model_instance, add):
        if (self.auto_now or
            (self.auto_now_add and add)) and model_instance.is_modified:
            value = timezone.now()
            setattr(model_instance, self.attname, value)
            return value
        return models.Field.pre_save(self, model_instance, add)


class LanguageBaseModel(models.Model):
    lang = models.CharField(_("Language"),
예제 #37
0
 def _get_local_name(language_code, language_name):
     try:
         return get_language_info(language_code)['name_local']
     except KeyError:
         return language_name
예제 #38
0
 def __unicode__(self):
     """
     Return the display name for this language.
     """
     return get_language_info(self.name)['name']
def get_local_language_names():
    locale.setlocale(locale.LC_ALL, "C.UTF-8")
    languages = []
    for lang in settings.LANGUAGES:
        languages.append([lang[0], get_language_info(lang[0])['name_local']])
    return sorted(languages, key=lambda x: locale.strxfrm(unicodedata.normalize('NFD', x[1])).casefold())
예제 #40
0
파일: admin.py 프로젝트: astagi/django-hvad
    def delete_translation(self, request, object_id, language_code):
        "The 'delete translation' admin view for this model."
        opts = self.model._meta
        app_label = opts.app_label
        translations_model = opts.translations_model

        try:
            obj = translations_model.objects.select_related('master').get(
                                                master__pk=unquote(object_id),
                                                language_code=language_code)
        except translations_model.DoesNotExist:
            raise Http404

        if not self.has_delete_permission(request, obj):
            raise PermissionDenied

        if len(obj.master.translations.all_languages()) <= 1:
            return self.deletion_not_allowed(request, obj, language_code)

        using = router.db_for_write(translations_model)

        # Populate deleted_objects, a data structure of all related objects that
        # will also be deleted.

        protected = False
        if django.VERSION >= (2, 1):
            deleted_objects, model_count, perms_needed, protected = get_deleted_objects(
                [obj], request, self.admin_site)
        else:
            deleted_objects, model_count, perms_needed, protected = get_deleted_objects(
                [obj], translations_model._meta, request.user, self.admin_site, using)

        lang = get_language_info(language_code)['name_local']

        if request.POST: # The user has already confirmed the deletion.
            if perms_needed:
                raise PermissionDenied
            obj_display = u'%s translation of %s' % (force_text(lang), force_text(obj.master))
            self.log_deletion(request, obj, obj_display)
            self.delete_model_translation(request, obj)

            self.message_user(request,
                _(u'The %(name)s "%(obj)s" was deleted successfully.') % {
                    'name': force_text(opts.verbose_name),
                    'obj': force_text(obj_display)
                }
            )

            if not self.has_change_permission(request, None):
                return HttpResponseRedirect(self.reverse('admin:index'))
            return HttpResponseRedirect(self.reverse('admin:%s_%s_changelist' % (opts.app_label, opts.model_name)))

        object_name = _(u'%s Translation') % force_text(opts.verbose_name)

        if perms_needed or protected:
            title = _(u"Cannot delete %(name)s") % {"name": object_name}
        else:
            title = _(u"Are you sure?")

        return render(
            request,
            self.delete_confirmation_template or (
                "admin/%s/%s/delete_confirmation.html" % (app_label, opts.object_name.lower()),
                "admin/%s/delete_confirmation.html" % app_label,
                "admin/delete_confirmation.html"
            ), {
                "title": title,
                "object_name": object_name,
                "object": obj,
                "deleted_objects": deleted_objects,
                "perms_lacking": perms_needed,
                "protected": protected,
                "opts": opts,
                "app_label": app_label,
            },
        )
예제 #41
0
def _default_context(request):
    if request.path.startswith('/control'):
        return {}

    ctx = {
        'css_file': None,
        'DEBUG': settings.DEBUG,
    }
    _html_head = []
    _html_page_header = []
    _html_foot = []
    _footer = []

    if hasattr(request, 'event'):
        pretix_settings = request.event.settings
    elif hasattr(request, 'organizer'):
        pretix_settings = request.organizer.settings
    else:
        pretix_settings = GlobalSettingsObject().settings

    text = pretix_settings.get('footer_text', as_type=LazyI18nString)
    link = pretix_settings.get('footer_link', as_type=LazyI18nString)

    if text:
        if link:
            _footer.append({'url': str(link), 'label': str(text)})
        else:
            ctx['footer_text'] = str(text)

    for receiver, response in global_html_page_header.send(None,
                                                           request=request):
        _html_page_header.append(response)
    for receiver, response in global_html_head.send(None, request=request):
        _html_head.append(response)
    for receiver, response in global_html_footer.send(None, request=request):
        _html_foot.append(response)
    for receiver, response in global_footer_link.send(None, request=request):
        if isinstance(response, list):
            _footer += response
        else:
            _footer.append(response)

    if hasattr(request, 'event') and get_scope():
        for receiver, response in html_head.send(request.event,
                                                 request=request):
            _html_head.append(response)
        for receiver, response in html_page_header.send(request.event,
                                                        request=request):
            _html_page_header.append(response)
        for receiver, response in html_footer.send(request.event,
                                                   request=request):
            _html_foot.append(response)
        for receiver, response in footer_link.send(request.event,
                                                   request=request):
            if isinstance(response, list):
                _footer += response
            else:
                _footer.append(response)

        if request.event.settings.presale_css_file:
            ctx['css_file'] = default_storage.url(
                request.event.settings.presale_css_file)

        ctx['event_logo'] = request.event.settings.get('logo_image',
                                                       as_type=str,
                                                       default='')[7:]
        try:
            ctx['social_image'] = request.event.cache.get_or_set(
                'social_image_url', request.event.social_image, 60)
        except:
            logger.exception('Could not generate social image')

        ctx['event'] = request.event
        ctx['languages'] = [
            get_language_info(code) for code in request.event.settings.locales
        ]

        if request.resolver_match:
            ctx['cart_namespace'] = request.resolver_match.kwargs.get(
                'cart_namespace', '')
    elif hasattr(request, 'organizer'):
        ctx['languages'] = [
            get_language_info(code)
            for code in request.organizer.settings.locales
        ]

    if hasattr(request, 'organizer'):
        if request.organizer.settings.presale_css_file and not hasattr(
                request, 'event'):
            ctx['css_file'] = default_storage.url(
                request.organizer.settings.presale_css_file)
        ctx['organizer_logo'] = request.organizer.settings.get(
            'organizer_logo_image', as_type=str, default='')[7:]
        ctx['organizer_homepage_text'] = request.organizer.settings.get(
            'organizer_homepage_text', as_type=LazyI18nString)
        ctx['organizer'] = request.organizer

    ctx['html_head'] = "".join(h for h in _html_head if h)
    ctx['html_foot'] = "".join(h for h in _html_foot if h)
    ctx['html_page_header'] = "".join(h for h in _html_page_header if h)
    ctx['footer'] = _footer
    ctx['site_url'] = settings.SITE_URL

    ctx['js_datetime_format'] = get_javascript_format_without_seconds(
        'DATETIME_INPUT_FORMATS')
    ctx['js_date_format'] = get_javascript_format_without_seconds(
        'DATE_INPUT_FORMATS')
    ctx['js_time_format'] = get_javascript_format_without_seconds(
        'TIME_INPUT_FORMATS')
    ctx['js_locale'] = get_moment_locale()
    ctx['html_locale'] = translation.get_language_info(
        get_language_without_region()).get('public_code',
                                           translation.get_language())
    ctx['settings'] = pretix_settings
    ctx['django_settings'] = settings

    return ctx
예제 #42
0
파일: models.py 프로젝트: codervince/lucky9
#!/usr/bin/python
# -*- coding: utf-8 -*-
from django.db import models
from django.conf import settings
from django.contrib.auth.models import User
from django.utils.translation import get_language_info
from django.utils.translation import ugettext_lazy as _

en_en = get_language_info('en')['name_local']
de_de = get_language_info('de')['name_local']
zh_cn = get_language_info('zh-hans')['name_local']
zh_tw = get_language_info('zh-hant')['name_local']
# ('zh_HK', '中文'),
# ('zh_CN', '官话'),


class UserProfile(models.Model):
    LANGUAGES = (
        ('en-us', en_en),
        ('zh-cn', zh_cn),
        ('zh-tw', zh_tw),
        ('de-de', de_de),
    )
    user = models.OneToOneField(
        User,
        on_delete=models.CASCADE,
        verbose_name=_('profile'),
    )
    # user = models.OneToOneField(User)
    joined = models.DateTimeField(auto_now_add=True)
    language = models.CharField(_('language'),
예제 #43
0
        "loggers": {
            "django.db.backends": {
                "level": "DEBUG",
                "handlers": ["console"]
            },
            "repanier": {
                "level": "DEBUG",
                "handlers": ["console"]
            },
        },
    }

####################### LANGUAGE

LANGUAGE_CODE = "fr"
LANGUAGES = [("fr", get_language_info("fr")["name_local"])]
CMS_LANGUAGES = {
    SITE_ID: [{
        "code": "fr",
        "name": get_language_info("fr")["name"],
        "public": True,
        "hide_untranslated": False,
    }]
}
PARLER_DEFAULT_LANGUAGE_CODE = LANGUAGE_CODE
PARLER_LANGUAGES = {
    SITE_ID: ({
        "code": LANGUAGE_CODE
    }, ),
    "default": {
        "fallbacks": [LANGUAGE_CODE],
예제 #44
0
    'default':
    dj_database_url.config(default="sqlite:///%s/db.sqlite3" % BASE_DIR),
}
kobocat_database_url = os.getenv('KC_DATABASE_URL')
if kobocat_database_url:
    DATABASES['kobocat'] = dj_database_url.parse(kobocat_database_url)

DATABASE_ROUTERS = ['kpi.db_routers.DefaultDatabaseRouter']

# Internationalization
# https://docs.djangoproject.com/en/1.8/topics/i18n/

django.conf.locale.LANG_INFO.update(EXTRA_LANG_INFO)

LANGUAGES = [
    (lang_code, get_language_info(lang_code)['name_local'])
    for lang_code in os.environ.get('DJANGO_LANGUAGE_CODES', 'en').split(' ')
]

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

LOCALE_PATHS = (os.path.join(BASE_DIR, 'locale'), )

USE_I18N = True

USE_L10N = True

USE_TZ = True
예제 #45
0
파일: mixins.py 프로젝트: MerlinB/mpicms
    def serve(self, request):
        lang = request.LANGUAGE_CODE
        if not getattr(self, 'body_' + lang) and self.body:
            messages.info(request, _('Page not available in ') + get_language_info(lang)['name_local'])

        return super().serve(request)
예제 #46
0
def supported_langs(request):
    from django.utils.translation import get_language_info
    supported_langs = (
        (get_language_info('en'), 'usa'),
        (get_language_info('es'), 'esp'),
        (get_language_info('tr'), 'tur'),
        (get_language_info('ja'), 'jpn'),
        (get_language_info('it'), 'ita'),
        (get_language_info('de'), 'deu'),
        (get_language_info('el'), 'grc'),
        (get_language_info('fr'), 'fra'),
        (get_language_info('he'), 'isr'),
        (get_language_info('ar'), 'sau'),
        (get_language_info('zh-cn'), 'chn'),
        (get_language_info('ru'), 'rus'),
        (get_language_info('nl'), 'nld'),
        (get_language_info('pt'), 'prt'),
        (get_language_info('hi'), 'ind'),
        (get_language_info('ko'), 'kor'),
    )
    return {'supported_langs': supported_langs}
예제 #47
0
                'level': 'INFO',
                'handlers': ['console'],
            },
            'repanier': {
                'level': 'DEBUG',
                'handlers': ['console'],
            },
        }
    }

####################### LANGUAGE
# if DJANGO_SETTINGS_LANGUAGE == 'fr':

LANGUAGE_CODE = 'fr'
LANGUAGES = [
    ('fr', get_language_info('fr')['name_local']),
]
CMS_LANGUAGES = {
    SITE_ID: [
        {
            'code': 'fr',
            'name': get_language_info('fr')['name'],
            'public': True,
            'hide_untranslated': False,
        },
    ]
}
PARLER_DEFAULT_LANGUAGE_CODE = LANGUAGE_CODE
PARLER_LANGUAGES = {
    SITE_ID: ({
        'code': LANGUAGE_CODE,
예제 #48
0
    def clean(self):
        if any(self.errors):
            # Don't bother validating the formset unless each form is valid on its own
            return

        if self.instance.id is None:
            if self.language_code != settings.LANGUAGE_CODE:
                # Important to also prohibit untranslated instance in settings.LANGUAGE_CODE
                self.add_error(
                    'long_name',
                    _('Please define first a long_name in %(language)s') % {
                        'language':
                        get_language_info(settings.LANGUAGE_CODE)['name_local']
                    })

        producer = self.cleaned_data.get("producer", None)
        if producer is None:
            self.add_error(
                'producer',
                _('Please select first a producer in the filter of previous screen'
                  ))
        else:
            reference = self.cleaned_data.get("reference", EMPTY_STRING)
            if reference:
                qs = Product.objects.filter(
                    reference=reference, producer_id=producer.id).order_by('?')
                if self.instance.id is not None:
                    qs = qs.exclude(id=self.instance.id)
                if qs.exists():
                    self.add_error(
                        "reference",
                        _('The reference is already used by %(product)s') %
                        {'product': qs.first()})

        order_unit = self.cleaned_data.get("order_unit", PRODUCT_ORDER_UNIT_PC)
        if order_unit != PRODUCT_ORDER_UNIT_DEPOSIT:
            producer_unit_price = self.cleaned_data["producer_unit_price"]
            if producer_unit_price < DECIMAL_ZERO:
                self.add_error(
                    'producer_unit_price',
                    _('The price must be greater than or equal to zero.'))

            customer_unit_price = self.cleaned_data.get(
                "customer_unit_price", DECIMAL_ZERO)
            if customer_unit_price < DECIMAL_ZERO:
                self.add_error(
                    'customer_unit_price',
                    _('The price must be greater than or equal to zero.'))

        if order_unit < PRODUCT_ORDER_UNIT_DEPOSIT:
            customer_minimum_order_quantity = self.cleaned_data.get(
                "customer_minimum_order_quantity", DECIMAL_ZERO)
            customer_increment_order_quantity = self.cleaned_data.get(
                "customer_increment_order_quantity", DECIMAL_ZERO)
            field_customer_alert_order_quantity_is_present = "customer_alert_order_quantity" in self.cleaned_data
            customer_alert_order_quantity = self.cleaned_data.get(
                "customer_alert_order_quantity", LIMIT_ORDER_QTY_ITEM)
            if not settings.REPANIER_SETTINGS_STOCK:
                limit_order_quantity_to_stock = False
            else:
                # Important, default for limit_order_quantity_to_stock is True, because this field is not displayed
                # if the pre-opening of offer is activated fro this producer.
                limit_order_quantity_to_stock = self.cleaned_data.get(
                    "limit_order_quantity_to_stock", True)
                if not limit_order_quantity_to_stock and producer is not None:
                    if producer.represent_this_buyinggroup:
                        self.add_error(
                            'limit_order_quantity_to_stock',
                            _('You must limit the order quantity to the stock because the producer represent this buyinggroup.'
                              ))
                    if producer.producer_pre_opening:
                        self.add_error(
                            'limit_order_quantity_to_stock',
                            _('You must limit the order quantity to the stock because you pre open the orders for this producer.'
                              ))

            if order_unit in [
                    PRODUCT_ORDER_UNIT_PC, PRODUCT_ORDER_UNIT_PC_PRICE_KG,
                    PRODUCT_ORDER_UNIT_PC_PRICE_LT,
                    PRODUCT_ORDER_UNIT_PC_PRICE_PC, PRODUCT_ORDER_UNIT_PC_KG
            ]:
                # Do not allow decimal value when the qty represents pieces.
                if customer_minimum_order_quantity != customer_minimum_order_quantity // 1:
                    self.add_error(
                        'customer_minimum_order_quantity',
                        _('The minimum order quantity must be an integer.'))
                if customer_increment_order_quantity != customer_increment_order_quantity // 1:
                    self.add_error('customer_increment_order_quantity',
                                   _('The increment must be an integer.'))
                if limit_order_quantity_to_stock:
                    stock = self.cleaned_data.get("stock", DECIMAL_ZERO)
                    if stock != stock // 1:
                        self.add_error('stock',
                                       _('The stock must be an integer.'))
                elif customer_alert_order_quantity != customer_alert_order_quantity // 1:
                    self.add_error('customer_alert_order_quantity',
                                   _('The alert quantity must be an integer.'))
            if customer_minimum_order_quantity <= DECIMAL_ZERO:
                self.add_error(
                    'customer_minimum_order_quantity',
                    _('The minimum order quantity must be greater than zero.'))

            if customer_minimum_order_quantity != customer_alert_order_quantity and customer_increment_order_quantity <= DECIMAL_ZERO:
                self.add_error('customer_increment_order_quantity',
                               _('The increment must be greater than zero.'))
            elif not limit_order_quantity_to_stock:
                if customer_increment_order_quantity <= customer_minimum_order_quantity:
                    if customer_minimum_order_quantity != customer_alert_order_quantity:
                        order_qty_item = (customer_alert_order_quantity -
                                          customer_minimum_order_quantity
                                          ) / customer_increment_order_quantity
                        q_max = customer_minimum_order_quantity + int(
                            order_qty_item) * customer_increment_order_quantity
                        if order_qty_item > (LIMIT_ORDER_QTY_ITEM - 1):
                            q_max = customer_minimum_order_quantity + LIMIT_ORDER_QTY_ITEM * customer_increment_order_quantity
                    else:
                        order_qty_item = DECIMAL_ONE
                        q_max = customer_alert_order_quantity
                else:
                    order_qty_item = customer_alert_order_quantity / customer_increment_order_quantity
                    q_max = int(
                        order_qty_item) * customer_increment_order_quantity
                    if order_qty_item > LIMIT_ORDER_QTY_ITEM:
                        q_max = customer_minimum_order_quantity + LIMIT_ORDER_QTY_ITEM * customer_increment_order_quantity
                if field_customer_alert_order_quantity_is_present:
                    if order_qty_item > LIMIT_ORDER_QTY_ITEM:
                        self.add_error(
                            'customer_alert_order_quantity',
                            _('This alert quantity will generate more than %(qty_item)d choices for the customer into the order form.'
                              ) % {
                                  'qty_item': LIMIT_ORDER_QTY_ITEM,
                              })
                    elif customer_alert_order_quantity < customer_minimum_order_quantity:
                        self.add_error(
                            'customer_alert_order_quantity',
                            _('The alert quantity must be greater than or equal to the minimum order quantity.'
                              ))
                    if q_max != customer_alert_order_quantity and q_max > customer_minimum_order_quantity:
                        self.add_error(
                            'customer_alert_order_quantity',
                            _('This alert quantity is not reachable. %(q_max)s is the best lower choice.'
                              ) % {'q_max': number_format(q_max, 3)})
예제 #49
0
    def _get_imported_transcripts(self, selected_lang):
        """
        Retrieve imported transcripts.
        *Imported transcripts are not listed in translation api.
        """
        api_endpoint = "http://api.3playmedia.com/caption_imports?apikey={api_key_3play}".format(
            api_key_3play=self.api_key)

        lang_endpoint = "http://api.3playmedia.com/caption_imports//available_languages?apikey={api_key_3play}".format(
            api_key_3play=self.api_key)

        try:
            response = urlopen(api_endpoint)
            data = response.read()
            imports_list = json.loads(data)
        except Exception as e:
            self.error = str(e.message)
        else:
            try:
                response = urlopen(lang_endpoint)
                data = response.read()
                lang_list = json.loads(data)
            except Exception:
                return
            else:
                lang_ids = {
                    d.get('language_id'): {
                        'name': d.get('full_name'),
                        'code': d.get('iso_639_1_code')
                    }
                    for d in lang_list
                }

                for caption_import in imports_list:
                    if caption_import['media_file_id'] == self.transcript_id:
                        lang_id = caption_import.get('language_id', 0)
                        language = lang_ids.get(lang_id).get('name')
                        lang_code = lang_ids.get(lang_id).get('code')
                        threeplay_id = caption_import.get(
                            'threeplay_transcript_id')

                        try:
                            lang_info = get_language_info(lang_code)
                            localized_name = lang_info.get('name_local')
                        except KeyError:
                            localized_name = language

                        if language and lang_code and threeplay_id:
                            self.imported_translations.append({
                                'threeplay_id':
                                threeplay_id,
                                'language':
                                language,
                                'lang_code':
                                lang_code,
                                'selected':
                                True if selected_lang in [language, lang_code]
                                else False,
                                'localized_name':
                                localized_name,
                                'dir':
                                'rtl' if language in RTL_LANGUAGES else 'ltr'
                            })
예제 #50
0
def contextprocessor(request):
    """
    Adds data to all template contexts
    """
    if request.path.startswith('/control'):
        return {}

    ctx = {
        'css_file': None,
        'DEBUG': settings.DEBUG,
    }
    _html_head = []
    _html_foot = []
    _footer = []

    if hasattr(request, 'event'):
        pretix_settings = request.event.settings
    elif hasattr(request, 'organizer'):
        pretix_settings = request.organizer.settings
    else:
        pretix_settings = GlobalSettingsObject().settings

    text = pretix_settings.get('footer_text', as_type=LazyI18nString)
    link = pretix_settings.get('footer_link', as_type=LazyI18nString)

    if text:
        if link:
            _footer.append({'url': str(link), 'label': str(text)})
        else:
            ctx['footer_text'] = str(text)

    if hasattr(request, 'event'):
        for receiver, response in html_head.send(request.event,
                                                 request=request):
            _html_head.append(response)
        for receiver, response in html_footer.send(request.event,
                                                   request=request):
            _html_foot.append(response)
        for receiver, response in footer_link.send(request.event,
                                                   request=request):
            if isinstance(response, list):
                _footer += response
            else:
                _footer.append(response)

        if request.event.settings.presale_css_file:
            ctx['css_file'] = default_storage.url(
                request.event.settings.presale_css_file)
        ctx['event_logo'] = request.event.settings.get('logo_image',
                                                       as_type=str,
                                                       default='')[7:]
        ctx['event'] = request.event
        ctx['languages'] = [
            get_language_info(code) for code in request.event.settings.locales
        ]

        if request.resolver_match:
            ctx['cart_namespace'] = request.resolver_match.kwargs.get(
                'cart_namespace', '')

    if hasattr(request, 'organizer'):
        if request.organizer.settings.presale_css_file and not hasattr(
                request, 'event'):
            ctx['css_file'] = default_storage.url(
                request.organizer.settings.presale_css_file)
        ctx['organizer_logo'] = request.organizer.settings.get(
            'organizer_logo_image', as_type=str, default='')[7:]
        ctx['organizer_homepage_text'] = request.organizer.settings.get(
            'organizer_homepage_text', as_type=LazyI18nString)
        ctx['organizer'] = request.organizer

    ctx['html_head'] = "".join(_html_head)
    ctx['html_foot'] = "".join(_html_foot)
    ctx['footer'] = _footer
    ctx['site_url'] = settings.SITE_URL

    return ctx
예제 #51
0
파일: i18n.py 프로젝트: zengxinhai/django
 def render(self, context):
     lang_code = self.lang_code.resolve(context)
     context[self.variable] = translation.get_language_info(lang_code)
     return ''
예제 #52
0
def cms_component_is_bidi(activated_language, languages):
    if any(code == activated_language for code, _ in languages):
        return translation.get_language_info(activated_language)['bidi']
    return False
예제 #53
0
def name_local(legal_code):
    return get_language_info(
        cc_to_django_language_code(legal_code.language_code))["name_local"]
예제 #54
0
def get_languages_with_local_name():
    """
    Get a list of tuples of available languages with local name.
    """
    return [(ll['code'], '%s (%s)' % (ll['name_local'], ll['code'])) for ll in
            [translation.get_language_info(l[0]) for l in settings.LANGUAGES]]
예제 #55
0
파일: i18n.py 프로젝트: zengxinhai/django
def language_name_local(lang_code):
    return translation.get_language_info(lang_code)['name_local']
예제 #56
0
파일: langs.py 프로젝트: qnst/bookfriend
# coding:utf-8
from django.utils.translation import get_language_info
from django.conf import settings

from django import template
register = template.Library()

LANGUAGES = []
for lang_code in settings.LANGUAGES_SUPPORTED:
    LANGUAGES.append(get_language_info(lang_code))


@register.inclusion_tag('parts/languages_select_part.html')
def language_select(default):
    return {'languages': LANGUAGES, 'default': default}


# 在模板中调用 setting 中的值,用法如:{% settings_value "LANGUAGE_CODE" %}
@register.simple_tag
def settings_value(name):
    return getattr(settings, name, "")
예제 #57
0
파일: i18n.py 프로젝트: zengxinhai/django
def language_bidi(lang_code):
    return translation.get_language_info(lang_code)['bidi']
예제 #58
0
def locale(request):
    return {'LOCALE_LANG': get_language_info(get_language())['name_local']}