How to use the weblate.trans.models.Unit function in Weblate

To help you get started, we’ve selected a few Weblate examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github WeblateOrg / weblate / weblate / trans / models.py View on Github external
# Was there change?
        was_new = False
        # Position of current unit
        pos = 1
        # Load translation file
        store = self.get_store()
        # Load translation template
        template_store = self.subproject.get_template_store()
        if template_store is None:
            for unit in store.units:
                # We care only about translatable strings
                # For some reason, blank string does not mean non translatable
                # unit in some formats (XLIFF), so let's skip those as well
                if not unit.istranslatable() or unit.isblank():
                    continue
                newunit, is_new = Unit.objects.update_from_unit(
                    self, unit, pos
                )
                was_new = was_new or (is_new and not newunit.translated)
                pos += 1
                try:
                    oldunits.remove(newunit.id)
                except:
                    pass
        else:
            for template_unit in template_store.units:
                # We care only about translatable strings
                # For some reason, blank string does not mean non translatable
                # unit in some formats (XLIFF), so let's skip those as well
                if not template_unit.istranslatable() or template_unit.isblank():
                    continue
                unit = store.findid(template_unit.getid())
github WeblateOrg / weblate / weblate / trans / views / search.py View on Github external
def parse_url(request, project, component=None, lang=None):
    context = {}
    if component is None:
        obj = get_project(request, project)
        unit_set = Unit.objects.filter(translation__component__project=obj)
        context['project'] = obj
    elif lang is None:
        obj = get_component(request, project, component)
        unit_set = Unit.objects.filter(translation__component=obj)
        context['component'] = obj
        context['project'] = obj.project
    else:
        obj = get_translation(request, project, component, lang)
        unit_set = obj.unit_set.all()
        context['translation'] = obj
        context['component'] = obj.component
        context['project'] = obj.component.project

    if not request.user.has_perm('unit.edit', obj):
        raise PermissionDenied()

    return obj, unit_set, context
github WeblateOrg / weblate / weblate / trans / views.py View on Github external
# Store unit
                        unit.target = merged.target
                        unit.fuzzy = merged.fuzzy
                        saved = unit.save_backend(request)
                        # Update stats if there was change
                        if saved:
                            profile.translated += 1
                            profile.save()
                        # Redirect to next entry
                        return HttpResponseRedirect('%s?type=%s&pos=%d%s' % (
                            obj.get_translate_url(),
                            rqtype,
                            pos,
                            search_url
                        ))
            except Unit.DoesNotExist:
                logger.error('message %s disappeared!', form.cleaned_data['checksum'])
                messages.error(request, _('Message you wanted to translate is no longer available!'))

    # Handle accepting/deleting suggestions
    if not locked and ('accept' in request.GET or 'delete' in request.GET):
        # Check for authenticated users
        if not request.user.is_authenticated():
            messages.error(request, _('You need to log in to be able to manage suggestions!'))
            return HttpResponseRedirect('%s?type=%s&pos=%d&dir=stay%s' % (
                obj.get_translate_url(),
                rqtype,
                pos,
                search_url
            ))

        # Parse suggestion ID
github WeblateOrg / weblate / weblate / trans / forms.py View on Github external
return None
        try:
            project = self.translation.component.project
            self.cleaned_data['merge_unit'] = merge_unit = Unit.objects.get(
                pk=self.cleaned_data['merge'],
                translation__component__project=project,
                translation__language=self.translation.language,
            )
            unit = self.cleaned_data['unit']
            if (
                unit.id_hash != merge_unit.id_hash
                and unit.content_hash != merge_unit.content_hash
                and unit.source != merge_unit.source
            ):
                raise ValidationError(_('Could not find merged string.'))
        except Unit.DoesNotExist:
            raise ValidationError(_('Could not find merged string.'))
        return self.cleaned_data
github WeblateOrg / weblate / weblate / memory / tasks.py View on Github external
def import_memory(project_id):
    from weblate.trans.models import Unit

    units = Unit.objects.filter(
        translation__component__project_id=project_id, state__gte=STATE_TRANSLATED
    )
    for unit in units.iterator():
        update_memory(None, unit)
github WeblateOrg / weblate / weblate / trans / views.py View on Github external
def show_check_project(request, name, project):
    '''
    Show checks failing in a project.
    '''
    prj = get_object_or_404(Project, slug=project)
    prj.check_acl(request)
    try:
        check = CHECKS[name]
    except KeyError:
        raise Http404('No check matches the given query.')
    units = Unit.objects.none()
    if check.target:
        langs = Check.objects.filter(
            check=name, project=prj, ignore=False
        ).values_list('language', flat=True).distinct()
        for lang in langs:
            checks = Check.objects.filter(
                check=name, project=prj, language=lang, ignore=False
            ).values_list('checksum', flat=True)
            res = Unit.objects.filter(
                checksum__in=checks,
                translation__language=lang,
                translation__subproject__project=prj,
                translated=True
            ).values(
                'translation__subproject__slug',
                'translation__subproject__project__slug'
github WeblateOrg / weblate / weblate / trans / views.py View on Github external
if not antispam.is_valid():
                # Silently redirect to next entry
                return HttpResponseRedirect('%s?type=%s&pos=%d%s' % (
                    obj.get_translate_url(),
                    rqtype,
                    pos,
                    search_url
                ))

        form = TranslationForm(request.POST)
        if form.is_valid() and not project_locked:
            # Check whether translation is not outdated
            obj.check_sync()
            try:
                try:
                    unit = Unit.objects.get(
                        checksum=form.cleaned_data['checksum'],
                        translation=obj
                    )
                except Unit.MultipleObjectsReturned:
                    # Possible temporary inconsistency caused by ongoing update
                    # of repo, let's pretend everyting is okay
                    unit = Unit.objects.filter(
                        checksum=form.cleaned_data['checksum'],
                        translation=obj
                    )[0]
                if 'suggest' in request.POST:
                    # Handle suggesion saving
                    user = request.user
                    if isinstance(user, AnonymousUser):
                        user = None
                    if form.cleaned_data['target'] == len(form.cleaned_data['target']) * ['']:
github WeblateOrg / weblate / weblate / addons / models.py View on Github external
@receiver(post_save, sender=Unit)
@disable_for_loaddata
def unit_post_save_handler(sender, instance, created, **kwargs):
    addons = Addon.objects.filter_event(
        instance.translation.component, EVENT_UNIT_POST_SAVE
    )
    for addon in addons:
        instance.translation.log_debug('running unit_post_save addon: %s', addon.name)
        addon.addon.unit_post_save(instance, created)
github WeblateOrg / weblate / weblate / trans / forms.py View on Github external
def clean(self):
        super(MergeForm, self).clean()
        if 'unit' not in self.cleaned_data or 'merge' not in self.cleaned_data:
            return None
        try:
            project = self.translation.component.project
            self.cleaned_data['merge_unit'] = merge_unit = Unit.objects.get(
                pk=self.cleaned_data['merge'],
                translation__component__project=project,
                translation__language=self.translation.language,
            )
            unit = self.cleaned_data['unit']
            if (unit.id_hash != merge_unit.id_hash and
                    unit.content_hash != merge_unit.content_hash and
                    unit.source != merge_unit.source):
                raise ValidationError(_('Could not find merged string.'))
        except Unit.DoesNotExist:
            raise ValidationError(_('Could not find merged string.'))
        return self.cleaned_data
github WeblateOrg / weblate / weblate / trans / autotranslate.py View on Github external
def process_others(self, source):
        """Perform automatic translation based on other components."""
        sources = Unit.objects.filter(
            translation__language=self.translation.language, state__gte=STATE_TRANSLATED
        )
        if source:
            subprj = Component.objects.get(id=source)

            if (
                not subprj.project.contribute_shared_tm
                and not subprj.project != self.translation.component.project
            ):
                raise PermissionDenied()
            sources = sources.filter(translation__component=subprj)
        else:
            project = self.translation.component.project
            sources = sources.filter(translation__component__project=project).exclude(
                translation=self.translation
            )