def filter_queryset_language(request, queryset):
    language = getattr(request, 'LANGUAGE_CODE')
    model = queryset.model
    if translation_pool.is_registered(model):
        info = translation_pool.get_info(model)
        filter_expr = '%s__%s' % (info.translation_join_filter, info.language_field)
    if translation_pool.is_registered_translation(model):
        info = translation_pool.get_info(model)
        filter_expr = '%s' % info.language_field
    if filter_expr:
        queryset = queryset.filter( \
            **{filter_expr: language}).distinct()
    return queryset
Esempio n. 2
0
def get_translation_filter(model, **kwargs):
    info = translation_pool.get_info(model)
    join_filter = info.translation_join_filter
    filter_dict = {}
    for key, value in kwargs.items():
        filter_dict['%s__%s' % (join_filter, key)] = value
    return filter_dict
Esempio n. 3
0
def translation_modelform_factory(model, form=TranslationModelForm, fields=None, exclude=None,
    formfield_callback=None):
    # Create the inner Meta class. FIXME: ideally, we should be able to
    # construct a ModelForm without creating and passing in a temporary
    # inner class.
    info = translation_pool.get_info(model)
    translated_model = info.translated_model
    translation_fields = [f[0].name for f in translated_model._meta.get_fields_with_model()]
    # Build up a list of attributes that the Meta object will have.
    attrs = {'model': model}
    if fields is not None:
        attrs['fields'] = [ field for field in fields if not field in translation_fields]
    if exclude is not None:
        attrs['exclude'] = exclude

    # If parent form class already has an inner Meta, the Meta we're
    # creating needs to inherit from the parent's inner meta.
    parent = (object,)
    if hasattr(form, 'Meta'):
        parent = (form.Meta, object)
    Meta = type('Meta', parent, attrs)

    # Give this new form class a reasonable name.
    class_name = model.__name__ + 'Form'

    # Class attributes for the new form class.
    form_class_attrs = {
        'Meta': Meta,
        'formfield_callback': formfield_callback
    }

    return TranslationModelFormMetaclass(class_name, (form,), form_class_attrs)
Esempio n. 4
0
    def render(self, name, value, attrs=None):
        
        hidden_input = super(LanguageWidget, self).render(name, value, attrs=attrs)
        lang_dict = dict(settings.LANGUAGES)
        
        current_languages = []
        translation_of_obj = self.translation_of_obj
        if translation_of_obj and translation_of_obj.pk:
            info = translation_pool.get_info(translation_of_obj.__class__)
            translation_of_obj = translation_pool.annotate_with_translations(translation_of_obj)
            for translation in translation_of_obj.translations:
                current_languages.append(getattr(translation, info.language_field))
                
        buttons = []
        for lang in settings.LANGUAGES:
            current_lang = lang[0] == value
            language_exists = lang[0] in current_languages
            button_classes = u'class="button%s"' % (
                current_lang and ' simple-translation-current' or language_exists and ' simple-translation-exists' or '',
            )
            disabled = current_lang and ' disabled="disabled"' or ''
            buttons.append(u''' <input onclick="trigger_lang_button(this,'./?language=%s');"
                %s name="%s" value="%s" type="button"%s />''' % (
                    lang[0], button_classes, lang[0], lang[1], disabled
                )
            )
                     
        if self.translation_obj.pk and len(current_languages) > 1:
            lang_descr = _('Delete %s translation') % force_unicode(lang_dict[str(value)])
            buttons.append(u'''<p class="deletelink-box simple-translation-delete"><a href="delete-translation/?language=%s" class="deletelink deletetranslation">%s</a></p>''' % (value, lang_descr))
                    
        tabs = u"""%s%s%s""" % (self.button_js, hidden_input, u''.join(buttons))

        return mark_safe(tabs)
Esempio n. 5
0
    def __init__(self, data=None, files=None, auto_id='id_%s', prefix=None,
        initial={}, error_class=ErrorList, label_suffix=':',
        empty_permitted=False, instance=None):
        
        model = self._meta.model
        child_model = self.child_form_class._meta.model
        info = translation_pool.get_info(model)
        
        current_language = self.base_fields[info.language_field].initial

        if instance and instance.pk:
            try:
                child_instance = child_model.objects.get(**{
                    info.translation_of_field: instance.pk,
                    info.language_field: current_language})
            except child_model.DoesNotExist:
                child_instance = child_model(**{
                    info.language_field: current_language})
        else:
            child_instance = child_model(**{info.language_field: current_language})
            
        initial.update(model_to_dict(child_instance))
        self.child_form = self.child_form_class(data=data, files=files, auto_id=auto_id, prefix=prefix,
            initial=initial, error_class=error_class, label_suffix=label_suffix,
            empty_permitted=empty_permitted, instance=child_instance)
            
        
        super(TranslationModelForm, self).__init__(data=data, files=files, auto_id=auto_id, prefix=prefix,
            initial=initial, error_class=error_class, label_suffix=label_suffix,
            empty_permitted=empty_permitted, instance=instance)
Esempio n. 6
0
def get_translation_filter(model, **kwargs):
    info = translation_pool.get_info(model)
    join_filter = info.translation_join_filter
    filter_dict = {}
    for key, value in list(kwargs.items()):
        filter_dict['%s__%s' % (join_filter, key)] = value
    return filter_dict
Esempio n. 7
0
    def __new__(cls, name, bases, attrs):
        formfield_callback = attrs.get('formfield_callback', None)
        try:
            parents = [b for b in bases if issubclass(b, TranslationModelForm)]
        except NameError:
            # We are defining TranslationModelForm itself.
            parents = None

        new_class = super(TranslationModelFormMetaclass,
                          cls).__new__(cls, name, bases, attrs)
        if not parents:
            return new_class

        opts = new_class._meta
        if opts.model:
            if translation_pool.is_registered(opts.model):
                info = translation_pool.get_info(opts.model)
                translated_model = info.translated_model
                new_class.child_form_class = modelform_factory(
                    translated_model,
                    exclude=[info.translation_of_field],
                    formfield_callback=formfield_callback)
                new_class.declared_fields.update(
                    new_class.child_form_class.declared_fields)
                new_class.base_fields.update(
                    new_class.child_form_class.base_fields)
        return new_class
Esempio n. 8
0
def filter_queryset_language(request, queryset):
    language = getattr(request, 'LANGUAGE_CODE', None)

    if not language:
        return queryset

    model = queryset.model
    filter_expr = None
    if translation_pool.is_registered(model):
        info = translation_pool.get_info(model)
        filter_expr = '%s__%s' % (info.translation_join_filter, info.language_field)
    if translation_pool.is_registered_translation(model):
        info = translation_pool.get_info(model)
        filter_expr = '%s' % info.language_field
    if filter_expr:
        queryset = queryset.filter( \
            **{filter_expr: language}).distinct()

    return queryset
Esempio n. 9
0
    def __init__(self,
                 data=None,
                 files=None,
                 auto_id='id_%s',
                 prefix=None,
                 initial={},
                 error_class=ErrorList,
                 label_suffix=':',
                 empty_permitted=False,
                 instance=None):

        model = self._meta.model
        child_model = self.child_form_class._meta.model
        info = translation_pool.get_info(model)

        current_language = self.base_fields[info.language_field].initial

        if instance and instance.pk:
            try:
                child_instance = child_model.objects.get(
                    **{
                        info.translation_of_field: instance.pk,
                        info.language_field: current_language
                    })
            except child_model.DoesNotExist:
                child_instance = child_model(
                    **{info.language_field: current_language})
        else:
            child_instance = child_model(
                **{info.language_field: current_language})

        initial.update(model_to_dict(child_instance))
        self.child_form = self.child_form_class(
            data=data,
            files=files,
            auto_id=auto_id,
            prefix=prefix,
            initial=initial,
            error_class=error_class,
            label_suffix=label_suffix,
            empty_permitted=empty_permitted,
            instance=child_instance)

        super(TranslationModelForm,
              self).__init__(data=data,
                             files=files,
                             auto_id=auto_id,
                             prefix=prefix,
                             initial=initial,
                             error_class=error_class,
                             label_suffix=label_suffix,
                             empty_permitted=empty_permitted,
                             instance=instance)
Esempio n. 10
0
def render_author_links(context, order_by='username'):
    request = context["request"]
    language = get_language_from_request(request)
    info = translation_pool.get_info(Entry)
    model = info.translated_model
    kw = get_translation_filter_language(Entry, language)
    return {
        'authors':
        auth_models.User.objects.filter(pk__in=model.objects.filter(
            entry__in=Entry.published.filter(
                **kw)).values('author')).order_by(order_by).values_list(
                    'username', flat=True)
    }
def render_author_links(context, order_by='username'):
    request = context["request"]
    language = get_language_from_request(request)
    info = translation_pool.get_info(Entry)
    model = info.translated_model
    kw = get_translation_filter_language(Entry, language)
    return {
        'authors': auth_models.User.objects.filter(
            pk__in=model.objects.filter(
                entry__in=Entry.published.filter(**kw)
            ).values('author')
        ).order_by(order_by).values_list('username', flat=True)
    }
Esempio n. 12
0
    def process_view(self, request, view_func, view_args, view_kwargs):
        language = None
        if "language_code" in view_kwargs:
            # get language and set tralslation
            language = view_kwargs.pop("language_code")
            translation.activate(language)
            request.LANGUAGE_CODE = translation.get_language()

        if not language:
            if not self.has_language_fallback_middlewares():
                super(MultilingualGenericsMiddleware, self).process_request(request)
            language = getattr(request, "LANGUAGE_CODE")

        if "queryset" in view_kwargs:
            filter_expr = None
            model = view_kwargs["queryset"].model
            if translation_pool.is_registered(model):
                info = translation_pool.get_info(model)
                filter_expr = "%s__%s" % (info.translation_join_filter, info.language_field)
            if translation_pool.is_registered_translation(model):
                info = translation_pool.get_info(model)
                filter_expr = "%s" % info.language_field
            if filter_expr:
                view_kwargs["queryset"] = view_kwargs["queryset"].filter(**{filter_expr: language}).distinct()
Esempio n. 13
0
    def render(self, name, value, attrs=None):

        hidden_input = super(LanguageWidget, self).render(name,
                                                          value,
                                                          attrs=attrs)
        lang_dict = dict(settings.LANGUAGES)

        current_languages = []
        translation_of_obj = self.translation_of_obj
        if translation_of_obj and translation_of_obj.pk:
            info = translation_pool.get_info(translation_of_obj.__class__)
            translation_of_obj = translation_pool.annotate_with_translations(
                translation_of_obj)
            for translation in translation_of_obj.translations:
                current_languages.append(
                    getattr(translation, info.language_field))

        buttons = []
        for lang in settings.LANGUAGES:
            current_lang = lang[0] == value
            language_exists = lang[0] in current_languages
            button_classes = u'class="button%s"' % (
                current_lang and ' simple-translation-current'
                or language_exists and ' simple-translation-exists' or '', )
            disabled = current_lang and ' disabled="disabled"' or ''
            buttons.append(
                u''' <input onclick="trigger_lang_button(this,'./?language=%s');"
                %s name="%s" value="%s" type="button"%s />''' %
                (lang[0], button_classes, lang[0], lang[1], disabled))

        if self.translation_obj.pk and len(current_languages) > 1:
            lang_descr = _('Delete %s translation') % force_text(
                lang_dict[str(value)])
            buttons.append(
                u'''<p class="deletelink-box simple-translation-delete"><a href="delete-translation/?language=%s" class="deletelink deletetranslation">%s</a></p>'''
                % (value, lang_descr))

        tabs = u"""%s%s%s""" % (self.button_js, hidden_input,
                                u''.join(buttons))

        return mark_safe(tabs)
Esempio n. 14
0
 def __new__(cls, name, bases, attrs):
     formfield_callback = attrs.get('formfield_callback', None)
     try:
         parents = [b for b in bases if issubclass(b, TranslationModelForm)]
     except NameError:
         # We are defining TranslationModelForm itself.
         parents = None
         
     new_class = super(TranslationModelFormMetaclass, cls).__new__(cls, name, bases,
             attrs)
     if not parents:
         return new_class
         
     opts = new_class._meta
     if opts.model:
         if translation_pool.is_registered(opts.model):
             info = translation_pool.get_info(opts.model)
             translated_model = info.translated_model
             new_class.child_form_class = modelform_factory(translated_model,
                 exclude=[info.translation_of_field], formfield_callback=formfield_callback)
             new_class.declared_fields.update(new_class.child_form_class.declared_fields)
             new_class.base_fields.update(new_class.child_form_class.base_fields)
     return new_class
Esempio n. 15
0
def translation_modelform_factory(model,
                                  form=TranslationModelForm,
                                  fields=None,
                                  exclude=None,
                                  formfield_callback=None):
    # Create the inner Meta class. FIXME: ideally, we should be able to
    # construct a ModelForm without creating and passing in a temporary
    # inner class.
    info = translation_pool.get_info(model)
    translated_model = info.translated_model
    translation_fields = [
        f[0].name for f in translated_model._meta.get_fields_with_model()
    ]
    # Build up a list of attributes that the Meta object will have.
    attrs = {'model': model}
    if fields is not None:
        attrs['fields'] = [
            field for field in fields if not field in translation_fields
        ]
    if exclude is not None:
        attrs['exclude'] = exclude

    # If parent form class already has an inner Meta, the Meta we're
    # creating needs to inherit from the parent's inner meta.
    parent = (object, )
    if hasattr(form, 'Meta'):
        parent = (form.Meta, object)
    Meta = type('Meta', parent, attrs)

    # Give this new form class a reasonable name.
    class_name = model.__name__ + 'Form'

    # Class attributes for the new form class.
    form_class_attrs = {'Meta': Meta, 'formfield_callback': formfield_callback}

    return TranslationModelFormMetaclass(class_name, (form, ),
                                         form_class_attrs)
    def __init__(self, *args, **kwargs):
        super(CustomEntryForm, self).__init__(*args, **kwargs)

        model = self._meta.model
        info = translation_pool.get_info(model)
        self.current_language = self.base_fields[info.language_field].initial
        title = None
        if self.instance and self.instance.pk:
            try:
                title = self.instance.entrytitle_set.get(
                    language=self.current_language)
            except ObjectDoesNotExist:
                pass

        publish = None
        if title:
            try:
                publish = EntryLanguagePublish.objects.get(
                    entry_title=title)
            except EntryLanguagePublish.DoesNotExist:
                pass

        self.initial['is_published'] = (
            publish and publish.is_published or False)
Esempio n. 17
0
def get_translation_filter_language(model, language, **kwargs):
    info = translation_pool.get_info(model)
    kwargs[info.language_field] = language
    return get_translation_filter(model, **kwargs)        
Esempio n. 18
0
 def __init__(self, *args, **kwargs):
     super(RealTranslationAdmin, self).__init__(*args, **kwargs)
     info = translation_pool.get_info(self.model)
     self.translated_model = info.translated_model
     self.translation_of_field = info.translation_of_field
     self.language_field = info.language_field
Esempio n. 19
0
def get_translation_filter_language(model, language, **kwargs):
    info = translation_pool.get_info(model)
    kwargs[info.language_field] = language
    return get_translation_filter(model, **kwargs)
Esempio n. 20
0
def get_translation_manager(obj):
    info = translation_pool.get_info(obj.__class__)
    return getattr(obj, info.translations_of_accessor)
Esempio n. 21
0
def get_translated_model(model):
    return translation_pool.get_info(model).translated_model   
Esempio n. 22
0
 def __init__(self, *args, **kwargs):
     super(RealTranslationAdmin, self).__init__(*args, **kwargs)
     info = translation_pool.get_info(self.model)
     self.translated_model = info.translated_model
     self.translation_of_field = info.translation_of_field
     self.language_field = info.language_field
Esempio n. 23
0
def get_translated_model(model):
    return translation_pool.get_info(model).translated_model
Esempio n. 24
0
def get_translation_manager(obj):
    info = translation_pool.get_info(obj.__class__)
    return getattr(obj, info.translations_of_accessor)