当前位置: 首页>>代码示例>>Python>>正文


Python utils.build_localized_fieldname函数代码示例

本文整理汇总了Python中modeltranslation.utils.build_localized_fieldname函数的典型用法代码示例。如果您正苦于以下问题:Python build_localized_fieldname函数的具体用法?Python build_localized_fieldname怎么用?Python build_localized_fieldname使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了build_localized_fieldname函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: modeltranslation_update_slugs

    def modeltranslation_update_slugs(sender, **kwargs):
        # https://bitbucket.org/neithere/django-autoslug/pull-request/11/modeltranslation-support-fix-issue-19/
        # http://django-modeltranslation.readthedocs.org
        #
        # TODO: tests
        #
        if not modeltranslation_utils:
            return

        instance = kwargs['instance']
        slugs = {}

        for field in instance._meta.fields:
            if type(field) == AutoSlugField:
                for lang in settings.LANGUAGES:
                    lang_code = lang[0]
                    lang_code = lang_code.replace('-', '_')

                    populate_from_localized = modeltranslation_utils.build_localized_fieldname(field.populate_from, lang_code)
                    populate_from_value = getattr(instance, populate_from_localized)

                    field_name_localized = modeltranslation_utils.build_localized_fieldname(field.name, lang_code)
                    field_value = getattr(instance, field_name_localized)

                    if not field_value or field.always_update:
                        slug = field.slugify(populate_from_value)
                        slugs[field_name_localized] = slug

        sender.objects.filter(pk=instance.pk).update(**slugs)
开发者ID:bahaddinyasar,项目名称:django-autoslugfield,代码行数:29,代码来源:fields.py

示例2: _patch_prepopulated_fields

 def _patch_prepopulated_fields(self):
     if self.prepopulated_fields:
         # prepopulated_fields_new = dict(self.prepopulated_fields)
         # for (k, v) in self.prepopulated_fields.items():
         #     if v[0] in self.trans_opts.fields:
         #         translation_fields = get_translation_fields(v[0])
         #         prepopulated_fields_new[k] = tuple([translation_fields[0]])
         prepopulated_fields_new = {}
         for (k, v) in self.prepopulated_fields.items():
             if k in self.trans_opts.fields:
                 translation_fields = [(l, build_localized_fieldname(k, l)) for l in AVAILABLE_LANGUAGES]
                 new_keys = tuple(translation_fields)
             else:
                 new_keys = ((None, k),)
             for lang, new_key in new_keys:
                 languages = AVAILABLE_LANGUAGES
                 if lang:
                     languages = [lang]
                 new_vals = []
                 for val in v:
                     if val in self.trans_opts.fields:
                         translation_fields = [build_localized_fieldname(val, l) for l in languages]
                         new_vals.extend(translation_fields)
                     else:
                         new_vals.append(val)
                 new_vals = tuple(new_vals)
                 prepopulated_fields_new[new_key] = new_vals
         self.prepopulated_fields = prepopulated_fields_new
开发者ID:chalkchisel,项目名称:django-modeltranslation,代码行数:28,代码来源:admin.py

示例3: test_sitemap_lang_slug

    def test_sitemap_lang_slug(self):
        """Test that the url is in the locale language"""
        site = Site.objects.get_current()
        from modeltranslation.utils import build_localized_fieldname  # pylint: disable=F0401

        kwargs1 = {}
        kwargs2 = {}

        for lang_code, lang_name in settings.LANGUAGES:
            loc_title_var = build_localized_fieldname('title', lang_code)
            loc_slug_var = build_localized_fieldname('slug', lang_code)
            kwargs1[loc_title_var] = 'article-{0}-1'.format(lang_name)
            kwargs2[loc_title_var] = 'other-article-{0}-2'.format(lang_name)
            kwargs1[loc_slug_var] = slugify(kwargs1[loc_title_var])
            kwargs2[loc_slug_var] = slugify(kwargs2[loc_title_var])

        article_class = get_article_class()

        article1 = mommy.make(article_class, publication=BaseArticle.PUBLISHED, **kwargs1)
        article2 = mommy.make(article_class, publication=BaseArticle.PUBLISHED, **kwargs2)

        factory = RequestFactory()
        request = factory.get('/sitemap.xml')
        response = sitemap_view(request, get_sitemaps())
        self.assertEqual(200, response.status_code)

        for (lang, name) in settings.LANGUAGES:
            activate(lang)
            self.assertContains(response, site.domain + article1.get_absolute_url())
            self.assertContains(response, site.domain + article2.get_absolute_url())
开发者ID:ljean,项目名称:coop_cms,代码行数:30,代码来源:test_sitemap.py

示例4: handle

 def handle(self, *args, **options):
     """command"""
     #look for emailing to be sent
     verbose = options.get('verbosity', 1)
     
     if not is_localized():
         print("the site is not localized this is not required")
     
     from modeltranslation.utils import build_localized_fieldname
     
     for alias in Alias.objects.all():
         cursor = connection.cursor()
         
         cursor.execute(
             '''SELECT path, redirect_url FROM coop_cms_alias where id={0}'''.format(alias.id))
         row = cursor.fetchone()
         print(row)
         (path, redirect_url) = row
         
         languages = [x for (x, y) in settings.LANGUAGES]
         
         lang_code = languages[0]
         path_field_name = build_localized_fieldname('path', lang_code)
         redirect_url_field_name = build_localized_fieldname('redirect_url', lang_code)
         if (not getattr(alias, path_field_name)) and (not getattr(alias, redirect_url_field_name)):
             print("update", alias.id, path, redirect_url)
             setattr(alias, path_field_name, path)
             setattr(alias, redirect_url_field_name, redirect_url)
             alias.save()
开发者ID:ljean,项目名称:coop_cms,代码行数:29,代码来源:patch_alias_translation.py

示例5: _new_set_url_path

def _new_set_url_path(self, parent):
    """
    This method override populates url_path for each specified language.
    This way we can get different urls for each language, defined
    by page slug.
    """
    for language in mt_settings.AVAILABLE_LANGUAGES:
        localized_slug_field = build_localized_fieldname('slug', language)
        default_localized_slug_field = build_localized_fieldname('slug', mt_settings.DEFAULT_LANGUAGE)
        localized_url_path_field = build_localized_fieldname('url_path', language)
        default_localized_url_path_field = build_localized_fieldname('url_path', mt_settings.DEFAULT_LANGUAGE)

        if parent:
            parent = parent.specific

            # Emulate the default behavior of django-modeltranslation to get the slug and url path
            # for the current language. If the value for the current language is invalid we get the one
            # for the default fallback language
            slug = getattr(self, localized_slug_field, None) or getattr(self, default_localized_slug_field, self.slug)
            parent_url_path = getattr(parent, localized_url_path_field, None) or \
                              getattr(parent, default_localized_url_path_field, parent.url_path)

            setattr(self, localized_url_path_field, parent_url_path + slug + '/')

        else:
            # a page without a parent is the tree root,
            # which always has a url_path of '/'
            setattr(self, localized_url_path_field, '/')

    # update url_path for children pages
    for child in self.get_children().specific():
        child.set_url_path(self.specific)
        child.save()

    return self.url_path
开发者ID:sinnwerkstatt,项目名称:wagtail-modeltranslation,代码行数:35,代码来源:patch_wagtailadmin.py

示例6: __get__

 def __get__(self, instance, owner):
     """
     Returns value from the translation field for the current language, or
     value for some another language according to fallback languages, or the
     custom fallback value, or field's default value.
     """
     if instance is None:
         return self
     default = NONE
     undefined = self.fallback_undefined
     if undefined is NONE:
         default = self.field.get_default()
         undefined = default
     langs = resolution_order(get_language(), self.fallback_languages)
     for lang in langs:
         loc_field_name = build_localized_fieldname(self.field.name, lang)
         val = getattr(instance, loc_field_name, None)
         if val is not None and val != undefined:
             return val
     if mt_settings.ENABLE_FALLBACKS and self.fallback_value is not NONE:
         return self.fallback_value
     else:
         if default is NONE:
             default = self.field.get_default()
         return default
开发者ID:masterdubs,项目名称:django-modeltranslation,代码行数:25,代码来源:fields.py

示例7: cache_name

 def cache_name(self):
     """
     Used in django 1.x
     """
     lang = get_language()
     cache = build_localized_fieldname(self.accessor, lang)
     return "_%s_cache" % cache
开发者ID:deschler,项目名称:django-modeltranslation,代码行数:7,代码来源:fields.py

示例8: add_localized_fields

def add_localized_fields(model):
    """
    Monkey patches the original model class to provide additional fields for
    every language. Only do that for fields which are defined in the
    translation options of the model.

    Returns a dict mapping the original fieldname to a list containing the
    names of the localized fields created for the original field.
    """
    localized_fields = dict()
    translation_opts = translator.get_options_for_model(model)
    for field_name in translation_opts.fields:
        localized_fields[field_name] = list()
        for l in settings.LANGUAGES:
            # Create a dynamic translation field
            translation_field = create_translation_field(
                model=model, field_name=field_name, lang=l[0])
            # Construct the name for the localized field
            localized_field_name = build_localized_fieldname(field_name, l[0])
            # Check if the model already has a field by that name
            if hasattr(model, localized_field_name):
                raise ValueError(
                    "Error adding translation field. Model '%s' already "
                    "contains a field named '%s'." % (
                        model._meta.object_name, localized_field_name))
            # This approach implements the translation fields as full valid
            # django model fields and therefore adds them via add_to_class
            model.add_to_class(localized_field_name, translation_field)
            localized_fields[field_name].append(localized_field_name)
    return localized_fields
开发者ID:mihaisucan,项目名称:django-modeltranslation,代码行数:30,代码来源:translator.py

示例9: __init__

    def __init__(self, translated_field, language, *args, **kwargs):
        # Update the dict of this field with the content of the original one
        # This might be a bit radical?! Seems to work though...
        self.__dict__.update(translated_field.__dict__)

        # Store the originally wrapped field for later
        self.translated_field = translated_field
        self.language = language

        # Translation are always optional (for now - maybe add some parameters
        # to the translation options for configuring this)

        if not isinstance(self, fields.BooleanField):
            # TODO: Do we really want to enforce null *at all*? Shouldn't this
            # better honour the null setting of the translated field?
            self.null = True
        self.blank = True

        # Adjust the name of this field to reflect the language
        self.attname = build_localized_fieldname(self.translated_field.name, self.language)
        self.name = self.attname

        # Copy the verbose name and append a language suffix
        # (will show up e.g. in the admin).
        self.verbose_name = build_localized_verbose_name(translated_field.verbose_name, language)
开发者ID:upsilonIT,项目名称:canesugar,代码行数:25,代码来源:fields.py

示例10: __get__

 def __get__(self, instance, owner):
     """
     Returns value from the translation field for the current language, or
     value for some another language according to fallback languages, or the
     custom fallback value, or field's default value.
     """
     if instance is None:
         return self
     default = NONE
     undefined = self.fallback_undefined
     if undefined is NONE:
         default = self.field.get_default()
         undefined = default
     langs = resolution_order(get_language(), self.fallback_languages)
     for lang in langs:
         loc_field_name = build_localized_fieldname(self.field.name, lang)
         val = getattr(instance, loc_field_name, None)
         if self.meaningful_value(val, undefined):
             return val
     if mt_settings.ENABLE_FALLBACKS and self.fallback_value is not NONE:
         return self.fallback_value
     else:
         if default is NONE:
             default = self.field.get_default()
         # Some fields like FileField behave strange, as their get_default() doesn't return
         # instance of attr_class, but rather None or ''.
         # Normally this case is handled in the descriptor, but since we have overridden it, we
         # must mock it up.
         if (isinstance(self.field, fields.files.FileField) and
                 not isinstance(default, self.field.attr_class)):
             return self.field.attr_class(instance, self.field, default)
         return default
开发者ID:GDGLima,项目名称:contentbox,代码行数:32,代码来源:fields.py

示例11: get_attname_column

 def get_attname_column(self):
     attname = self.get_attname()
     column = (
         build_localized_fieldname(self.translated_field.db_column or self.translated_field.name, self.language)
         or attname
     )
     return attname, column
开发者ID:benjaoming,项目名称:django-modeltranslation,代码行数:7,代码来源:fields.py

示例12: __init__

 def __init__(self):
     super(Command, self).__init__()
     update_fields = ['url_path']
     for language in mt_settings.AVAILABLE_LANGUAGES:
         localized_url_path = build_localized_fieldname('url_path', language)
         update_fields.append(localized_url_path)
     self.update_fields = update_fields
开发者ID:infoportugal,项目名称:wagtail-modeltranslation,代码行数:7,代码来源:set_translation_url_paths.py

示例13: add_translation_fields

def add_translation_fields(model, opts):
    """
    Monkey patches the original model class to provide additional fields for
    every language.

    Adds newly created translation fields to the given translation options.
    """
    model_empty_values = getattr(opts, 'empty_values', NONE)
    for field_name in opts.local_fields.keys():
        field_empty_value = parse_field(model_empty_values, field_name, NONE)
        for l in mt_settings.AVAILABLE_LANGUAGES:
            # Create a dynamic translation field
            translation_field = create_translation_field(
                model=model, field_name=field_name, lang=l, empty_value=field_empty_value)
            # Construct the name for the localized field
            localized_field_name = build_localized_fieldname(field_name, l)
            # Check if the model already has a field by that name
            if hasattr(model, localized_field_name):
                raise ValueError(
                    "Error adding translation field. Model '%s' already contains a field named"
                    "'%s'." % (model._meta.object_name, localized_field_name))
            # This approach implements the translation fields as full valid
            # django model fields and therefore adds them via add_to_class
            model.add_to_class(localized_field_name, translation_field)
            opts.add_translation_field(field_name, translation_field)

    # Rebuild information about parents fields. If there are opts.local_fields, field cache would be
    # invalidated (by model._meta.add_field() function). Otherwise, we need to do it manually.
    if len(opts.local_fields) == 0:
        model._meta._fill_fields_cache()
开发者ID:Kniyl,项目名称:django-modeltranslation,代码行数:30,代码来源:translator.py

示例14: __init__

    def __init__(self, translated_field, language, *args, **kwargs):
        # Store the originally wrapped field for later
        self.translated_field = translated_field
        self.language = language
        
        # Update the dict of this field with the content of the original one
        # This might be a bit radical?! Seems to work though...
        self.__dict__.update(translated_field.__dict__)        
        
        # Translation are always optional (for now - maybe add some parameters
        # to the translation options for configuring this)
        self.null = True
        self.blank = True

        # If translations are optional, uniqueness can't be enforced
        self._unique = False
        
        # Adjust the name of this field to reflect the language
        self.attname = build_localized_fieldname(translated_field.name, language)
        self.name = self.attname
        
        # Copy the verbose name and append a language suffix (will e.g. in the
        # admin). This might be a proxy function so we have to check that here.
        if hasattr(translated_field.verbose_name, '_proxy____unicode_cast'):            
            verbose_name = translated_field.verbose_name._proxy____unicode_cast()
        else:
            verbose_name = translated_field.verbose_name                       
        self.verbose_name = '%s [%s]' % (verbose_name, language)
开发者ID:dantium,项目名称:django-modeltranslation,代码行数:28,代码来源:fields.py

示例15: rewrite_lookup_key

def rewrite_lookup_key(model, lookup_key):
    translatable_fields = get_translatable_fields_for_model(model)
    if translatable_fields is not None:
        pieces = lookup_key.split('__')
        # If we are doing a lookup on a translatable field,
        # we want to rewrite it to the actual field name
        # For example, we want to rewrite "name__startswith" to "name_fr__startswith"
        if pieces[0] in translatable_fields:
            lookup_key = build_localized_fieldname(pieces[0], get_language())

            remaining_lookup = '__'.join(pieces[1:])
            if remaining_lookup:
                lookup_key = '%s__%s' % (lookup_key, remaining_lookup)

    pieces = lookup_key.split('__')
    if len(pieces) > 1:
        # Check if we are doing a lookup to a related trans model
        fields_to_trans_models = get_fields_to_translatable_models(model)
        for field_to_trans, transmodel in fields_to_trans_models:
            if pieces[0] == field_to_trans:
                sub_lookup = '__'.join(pieces[1:])
                if sub_lookup:
                    sub_lookup = rewrite_lookup_key(transmodel, sub_lookup)
                    lookup_key = '%s__%s' % (pieces[0], sub_lookup)
                break

    return lookup_key
开发者ID:pigletto,项目名称:django-modeltranslation,代码行数:27,代码来源:manager.py


注:本文中的modeltranslation.utils.build_localized_fieldname函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。