Esempio n. 1
0
    def rewrite_trans_fields(cls, local_trans_fields, attrs):
        """Create copies of the local translatable fields for each language"""
        for field in local_trans_fields:

            for lang in settings.LANGUAGES[1:]:
                lang_code = lang[0]

                lang_field = copy.copy(attrs[field])
                # The new field cannot have the same creation_counter (else the ordering will be arbitrary)
                # We increment by a decimal point because we don't want to have
                # to adjust the creation_counter of ALL other subsequent fields
                lang_field.creation_counter += 0.0001  # Limitation this trick: only supports upto 10,000 languages
                lang_fieldname = get_real_field_name(field, lang_code)
                lang_field.name = lang_fieldname

                if lang_field.verbose_name is not None:
                    # This is to extract the original value that was passed into ugettext_lazy
                    # We do this so that we avoid evaluating the lazy object.
                    raw_verbose_name = lang_field.verbose_name._proxy____args[
                        0]
                else:
                    raw_verbose_name = field.replace('-', ' ')
                lang_field.verbose_name = _(
                    u'%(verbose_name)s (%(language)s)' % {
                        'verbose_name': raw_verbose_name,
                        'language': lang[1]
                    })

                attrs[lang_fieldname] = lang_field

        return attrs
Esempio n. 2
0
    def rewrite_trans_fields(cls, local_trans_fields, attrs):
        """Create copies of the local translatable fields for each language"""
        for field in local_trans_fields:

            for lang in settings.LANGUAGES[1:]:
                lang_code = lang[0]

                lang_field = copy.copy(attrs[field])
                # The new field cannot have the same creation_counter (else the ordering will be arbitrary)
                # We increment by a decimal point because we don't want to have
                # to adjust the creation_counter of ALL other subsequent fields
                lang_field.creation_counter += 0.0001  # Limitation this trick: only supports upto 10,000 languages
                lang_fieldname = get_real_field_name(field, lang_code)
                lang_field.name = lang_fieldname

                if lang_field.verbose_name is not None:
                    # This is to extract the original value that was passed into ugettext_lazy
                    # We do this so that we avoid evaluating the lazy object.
                    raw_verbose_name = lang_field.verbose_name._proxy____args[0]
                else:
                    raw_verbose_name = field.replace('-', ' ')
                lang_field.verbose_name = _(u'%(verbose_name)s (%(language)s)' %
                    {'verbose_name': raw_verbose_name, 'language': lang[1]}
                )

                attrs[lang_fieldname] = lang_field

        return attrs
Esempio n. 3
0
def rewrite_lookup_key(model, lookup_key):
    from linguo.models import MultilingualModel  # to avoid circular import
    if issubclass(model, MultilingualModel):
        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 model._meta.translatable_fields:
            lookup_key = get_real_field_name(pieces[0], get_language().split('-')[0])

            remaining_lookup = '__'.join(pieces[1:])
            if remaining_lookup:
                lookup_key = '%s__%s' % (lookup_key, remaining_lookup)
        elif pieces[0] in map(lambda field: '%s_%s' % (field, settings.LANGUAGES[0][0]), model._meta.translatable_fields):
            # If the lookup field explicitly refers to the primary langauge (eg. "name_en"),
            # we want to rewrite that to point to the actual field name.
            lookup_key = pieces[0][:-3]  # Strip out the language suffix
            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
Esempio n. 4
0
    def __init__(self, *args, **kwargs):
        # Set the language for this instance
        if "language" in kwargs:
            lang_codes = [lang[0] for lang in settings.LANGUAGES]
            if kwargs["language"] not in lang_codes:
                raise ValidationError(u"'%(language)s' is not a valid language." % {"language": kwargs["language"]})

            self._language = kwargs["language"]
            if "language" not in self._meta.get_all_field_names():
                del kwargs["language"]
        else:
            self._language = get_language().split("-")[0]
        # Rewrite any keyword arguments for translatable fields
        for field in self._meta.translatable_fields:
            if field in kwargs.keys():
                attrname = get_real_field_name(field, self._language)
                if attrname != field:
                    kwargs[attrname] = kwargs[field]
                    del kwargs[field]

        # We have to switch to the primary language before initializing
        # or else the wrong value will be set for the non-primary language if activated
        language = self._language
        self._language = settings.LANGUAGES[0][0]
        super(MultilingualModel, self).__init__(*args, **kwargs)
        self._language = language
Esempio n. 5
0
    def __init__(self, *args, **kwargs):
        self._force_language = None

        # Rewrite any keyword arguments for translatable fields
        language = get_language().split('-')[0]
        for field in self._meta.translatable_fields:
            if field in kwargs.keys():
                attrname = get_real_field_name(field, language)
                if attrname != field:
                    kwargs[attrname] = kwargs[field]
                    del kwargs[field]

        # We have to force the primary language before initializing or else
        # our "proxy" property will prevent the primary language values from being returned.
        self._force_language = settings.LANGUAGES[0][0]
        super(MultilingualModel, self).__init__(*args, **kwargs)
        self._force_language = None
Esempio n. 6
0
    def __init__(self, *args, **kwargs):
        self._force_language = None

        # Rewrite any keyword arguments for translatable fields
        language = get_language().split('-')[0]
        for field in self._meta.translatable_fields:
            if field in kwargs.keys():
                attrname = get_real_field_name(field, language)
                if attrname != field:
                    kwargs[attrname] = kwargs[field]
                    del kwargs[field]

        # We have to force the primary language before initializing or else
        # our "proxy" property will prevent the primary language values from being returned.
        self._force_language = settings.LANGUAGES[0][0]
        super(MultilingualModel, self).__init__(*args, **kwargs)
        self._force_language = None
Esempio n. 7
0
    def rewrite_unique_together(cls, local_trans_fields, attrs):
        if ('Meta'
                not in attrs) or not hasattr(attrs['Meta'], 'unique_together'):
            return attrs

        # unique_together can be either a tuple of tuples, or a single
        # tuple of two strings. Normalize it to a tuple of tuples.
        ut = attrs['Meta'].unique_together
        if ut and not isinstance(ut[0], (tuple, list)):
            ut = (ut, )

        # Determine which constraints need to be rewritten
        new_ut = []
        constraints_to_rewrite = []
        for constraint in ut:
            needs_rewriting = False
            for field in constraint:
                if field in local_trans_fields:
                    needs_rewriting = True
                    break
            if needs_rewriting:
                constraints_to_rewrite.append(constraint)
            else:
                new_ut.append(constraint)

        # Now perform the re-writing
        for constraint in constraints_to_rewrite:
            for lang in settings.LANGUAGES:
                lang_code = lang[0]
                new_constraint = []
                for field in constraint:
                    if field in local_trans_fields:
                        field = get_real_field_name(field, lang_code)
                    new_constraint.append(field)

                new_ut.append(tuple(new_constraint))

        attrs['Meta'].unique_together = tuple(new_ut)
        return attrs
Esempio n. 8
0
    def rewrite_unique_together(cls, local_trans_fields, attrs):
        if ('Meta' not in attrs) or not hasattr(attrs['Meta'], 'unique_together'):
            return attrs

        # unique_together can be either a tuple of tuples, or a single
        # tuple of two strings. Normalize it to a tuple of tuples.
        ut = attrs['Meta'].unique_together
        if ut and not isinstance(ut[0], (tuple, list)):
            ut = (ut,)

        # Determine which constraints need to be rewritten
        new_ut = []
        constraints_to_rewrite = []
        for constraint in ut:
            needs_rewriting = False
            for field in constraint:
                if field in local_trans_fields:
                    needs_rewriting = True
                    break
            if needs_rewriting:
                constraints_to_rewrite.append(constraint)
            else:
                new_ut.append(constraint)

        # Now perform the rewritting
        for constraint in constraints_to_rewrite:
            for lang in settings.LANGUAGES:
                language = lang[0]
                new_constraint = []
                for field in constraint:
                    if field in local_trans_fields:
                        field = get_real_field_name(field, language)
                    new_constraint.append(field)

                new_ut.append(tuple(new_constraint))

        attrs['Meta'].unique_together = tuple(new_ut)
        return attrs
Esempio n. 9
0
def rewrite_lookup_key(model, lookup_key):
    from linguo.models import MultilingualModel  # to avoid circular import
    if issubclass(model, MultilingualModel):
        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 model._meta.translatable_fields:
            lookup_key = get_real_field_name(pieces[0],
                                             get_language().split('-')[0])

            remaining_lookup = '__'.join(pieces[1:])
            if remaining_lookup:
                lookup_key = '%s__%s' % (lookup_key, remaining_lookup)
        elif pieces[0] in map(
                lambda field: '%s_%s' % (field, settings.LANGUAGES[0][0]),
                model._meta.translatable_fields):
            # If the lookup field explicitly refers to the primary langauge (eg. "name_en"),
            # we want to rewrite that to point to the actual field name.
            lookup_key = pieces[0][:-3]  # Strip out the language suffix
            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
Esempio n. 10
0
def rewrite_lookup_key(model, lookup_key):
    from linguo.models import MultilingualModel # to avoid circular import
    if issubclass(model, MultilingualModel):
        pieces = lookup_key.split('__')
        if pieces[0] in model._meta.translatable_fields:
            lookup_key = get_real_field_name(pieces[0], get_language().split('-')[0])

            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