def update_translations(request): """ Update translations: delete orphan translations and creates empty translations for new objects in database. """ FieldTranslation.delete_orphan_translations() num_translations = FieldTranslation.update_translations() return render_to_response('modeltranslation/admin/update_translations_ok.html',{"num_translations":num_translations}, RequestContext(request))
def export_translations(request, language): """ Vista de exportación de las traducciones """ FieldTranslation.delete_orphan_translations() translations = FieldTranslation.objects.filter(lang=language) for trans in translations: trans.source_text = trans.source_text.replace("'", "\'").replace( "\"", "\\\"") trans.translation = trans.translation.replace("'", "\'").replace( "\"", "\\\"") replacements = {"translations": translations, "lang": language} if len(settings.ADMINS) > 0: replacements["last_translator"] = settings.ADMINS[0][0] replacements["last_translator_email"] = settings.ADMINS[0][1] if settings.WEBSITE_NAME: replacements["website_name"] = settings.WEBSITE_NAME response = render( request=request, template_name='modeltranslation/admin/export_translations.po', dictionary=replacements, context_instance=RequestContext(request), content_type="text/x-gettext-translation") response['Content-Disposition'] = 'attachment; filename="{0}.po"'.format( language) return response
def update_translations(request): """ Actualiza las traducciones eliminando las huérfanas y generando traducciones vacías para todos los objetos que existan en base de datos. """ FieldTranslation.delete_orphan_translations() num_translations = FieldTranslation.update_translations() return render_to_response('modeltranslation/admin/update_translations_ok.html',{"num_translations":num_translations}, RequestContext(request))
def update_translations(request): """ Actualiza las traducciones eliminando las huérfanas y generando traducciones vacías para todos los objetos que existan en base de datos. """ FieldTranslation.delete_orphan_translations() num_translations = FieldTranslation.update_translations() return render_to_response( 'modeltranslation/admin/update_translations_ok.html', {"num_translations": num_translations}, RequestContext(request))
def _save_translations(sender, instance, *args, **kwargs): """ This signal saves model translations. """ # If we are in a site with one language there is no need of saving translations if site_is_monolingual(): return False cls = sender # If its class has no "translatable_fields" then there are no translations if not hasattr(cls._meta, "translatable_fields"): return False # For each translatable field, get its value, computes its md5 and for each language creates its # empty translation. for field in cls._meta.translatable_fields: value = getattr(instance, field) if not value is None: md5_value = checksum(value) setattr(instance, u"md5" + field, md5_value) for lang in settings.LANGUAGES: lang = lang[0] # print "({0}!={1}) = {2}".format(lang, settings.LANGUAGE_CODE,lang!=settings.LANGUAGE_CODE) if lang != settings.LANGUAGE_CODE: context = u"Updating from object" if hasattr(instance, "trans_context"): context = getattr(instance, "trans_context") trans = FieldTranslation.update(instance, field, lang, context)
def _save_translations(sender, instance, *args, **kwargs): """ This signal saves model translations. """ # If we are in a site with one language there is no need of saving translations if site_is_monolingual(): return False cls = sender # If its class has no "translatable_fields" then there are no translations if not hasattr(cls._meta, "translatable_fields"): return False # For each translatable field, get its value, computes its md5 and for each language creates its # empty translation. for field in cls._meta.translatable_fields: value = getattr(instance,field) if not value is None: md5_value = checksum(value) setattr( instance, u"md5"+field, md5_value ) for lang in settings.LANGUAGES: lang = lang[0] # print "({0}!={1}) = {2}".format(lang, settings.LANGUAGE_CODE,lang!=settings.LANGUAGE_CODE) if lang != settings.LANGUAGE_CODE: context = u"Updating from object" if hasattr(instance, "trans_context"): context = getattr(instance, "trans_context") trans = FieldTranslation.update(instance, field, lang, context)
def _import_po_file(uploadedfile, lang): lines = [] for line in uploadedfile: lines.append(line) num_lines = len(lines) prog_ctxt = re.compile(r"msgctxt\s+\"(?P<id>\d+)--(?P<module>(\.\w)+)--(?P<model>\w+)--(?P<object_id>\d+)--(?P<field>\w+)\"") prog_msgid = re.compile(r"msgid\s+\"(?P<source_text>.+)\"$") prog_msgstr = re.compile(r"msgstr\s+(?P<trans>.+)") i = 0 while i < num_lines: line = lines[i] result = prog_ctxt.match(line) if result: id = result.group("id") is_fuzzy = (lines[i-1] == "#, fuzzy\n") source_text = lines[i+1] translation_line = lines[i+2] # Traducción g = prog_msgstr.match(translation_line) if g is None: i += 1 continue translation = g.group("trans").replace("msgstr","")[1:-1].replace("\\\"","\"").replace('\\\'','\'') # Get translation from a translation id try: field_trans = FieldTranslation.objects.get(id=id) except FieldTranslation.DoesNotExist: source_text = source_text.replace("msgid","")[1:-1].replace("\\\"","\"").replace('\\\'','\'') source_md5 = hashlib.md5(source_text.encode("utf-8")).hexdigest() field_trans = FieldTranslation( module=result.group("module"), model=result.group("model"), object_id=result.group("object_id"), field=result.group("field"), lang=lang, source_text=source_text, source_md5=source_md5 ) # Sets translation and is_fuzzy attribute field_trans.translation = translation field_trans.is_fuzzy = is_fuzzy field_trans.save() i += 4 i += 1
def export_translations(request, language): """ Export translations view. """ FieldTranslation.delete_orphan_translations() translations = FieldTranslation.objects.filter(lang=language) for trans in translations: trans.source_text = trans.source_text.replace("'","\'").replace("\"","\\\"") trans.translation = trans.translation.replace("'","\'").replace("\"","\\\"") replacements = {"translations":translations, "lang":language} if len(settings.ADMINS)>0: replacements["last_translator"] = settings.ADMINS[0][0] replacements["last_translator_email"] = settings.ADMINS[0][1] if settings.WEBSITE_NAME: replacements["website_name"] = settings.WEBSITE_NAME response = render(request=request, template_name='modeltranslation/admin/export_translations.po', dictionary=replacements, context_instance=RequestContext(request), content_type="text/x-gettext-translation") response['Content-Disposition'] = 'attachment; filename="{0}.po"'.format(language) return response
def _make_translations(obj): cls = obj.__class__ obj.classname = cls.__name__ if hasattr(cls,"TRANSLATABLE_FIELDS"): for field in cls.TRANSLATABLE_FIELDS: value = getattr(obj,field) md5_value = hashlib.md5(value.encode("utf-8")).hexdigest() setattr( obj, "md5"+field, md5_value ) for lang in settings.LANGUAGES: trans = FieldTranslation.update(obj, field, lang[0])
def _make_translations(obj): cls = obj.__class__ obj.classname = cls.__name__ if hasattr(cls, "TRANSLATABLE_FIELDS"): for field in cls.TRANSLATABLE_FIELDS: value = getattr(obj, field) md5_value = hashlib.md5(value.encode("utf-8")).hexdigest() setattr(obj, "md5" + field, md5_value) for lang in settings.LANGUAGES: trans = FieldTranslation.update(obj, field, lang[0])
def _import_po_file(uploadedfile, lang): lines = [] for line in uploadedfile: lines.append(line) num_lines = len(lines) prog_ctxt = re.compile( r"msgctxt\s+\"(?P<id>\d+)--(?P<model>\w+)--(?P<object_id>\d+)--(?P<field>\w+)\"" ) prog_msgid = re.compile(r"msgid\s+\"(?P<source_text>.+)\"$") prog_msgstr = re.compile(r"msgstr\s+(?P<trans>.+)") i = 0 while i < num_lines: line = lines[i] result = prog_ctxt.match(line) if result: id = result.group("id") is_fuzzy = (lines[i - 1] == "#, fuzzy\n") source_text = lines[i + 1] translation_line = lines[i + 2] # Traducción g = prog_msgstr.match(translation_line) if g is None: i += 1 continue translation = g.group("trans").replace( "msgstr", "")[1:-1].replace("\\\"", "\"").replace('\\\'', '\'') # Obtención de la traducción a partir del id try: field_trans = FieldTranslation.objects.get(id=id) except FieldTranslation.DoesNotExist: source_text = source_text.replace( "msgid", "")[1:-1].replace("\\\"", "\"").replace('\\\'', '\'') source_md5 = hashlib.md5( source_text.encode("utf-8")).hexdigest() field_trans = FieldTranslation( model=result.group("model"), object_id=result.group("object_id"), field=result.group("field"), lang=lang, source_text=source_text, source_md5=source_md5) # Establecemos la traducción y si es fuzzy field_trans.translation = translation field_trans.is_fuzzy = is_fuzzy field_trans.save() #print translation #print is_fuzzy i += 4 i += 1
def import_translations(request, language): """ Importa las traducciones a partir de un archivo PO. Ten en cuenta que el archivo PO ha de ser generado desde esta aplicación, de forma que los comentarios sirvan como id de traducción (lo metemos nosotros en la exportación). """ def _import_po_file(uploadedfile, lang): lines = [] for line in uploadedfile: lines.append(line) num_lines = len(lines) prog_ctxt = re.compile( r"msgctxt\s+\"(?P<id>\d+)--(?P<model>\w+)--(?P<object_id>\d+)--(?P<field>\w+)\"" ) prog_msgid = re.compile(r"msgid\s+\"(?P<source_text>.+)\"$") prog_msgstr = re.compile(r"msgstr\s+(?P<trans>.+)") i = 0 while i < num_lines: line = lines[i] result = prog_ctxt.match(line) if result: id = result.group("id") is_fuzzy = (lines[i - 1] == "#, fuzzy\n") source_text = lines[i + 1] translation_line = lines[i + 2] # Traducción g = prog_msgstr.match(translation_line) if g is None: i += 1 continue translation = g.group("trans").replace( "msgstr", "")[1:-1].replace("\\\"", "\"").replace('\\\'', '\'') # Obtención de la traducción a partir del id try: field_trans = FieldTranslation.objects.get(id=id) except FieldTranslation.DoesNotExist: source_text = source_text.replace( "msgid", "")[1:-1].replace("\\\"", "\"").replace('\\\'', '\'') source_md5 = hashlib.md5( source_text.encode("utf-8")).hexdigest() field_trans = FieldTranslation( model=result.group("model"), object_id=result.group("object_id"), field=result.group("field"), lang=lang, source_text=source_text, source_md5=source_md5) # Establecemos la traducción y si es fuzzy field_trans.translation = translation field_trans.is_fuzzy = is_fuzzy field_trans.save() #print translation #print is_fuzzy i += 4 i += 1 # Elimina traducciones que no estén asociadas a ningún objeto FieldTranslation.delete_orphan_translations() # Acceso obligatoriamente por POST if request.method != "POST": return HttpResponseRedirect(reverse("modeltranslation:admin_url")) form = ImportTranslationsForm(request.POST, request.FILES) if form.is_valid(): _import_po_file(request.FILES['file'], language) #cache = TransCache.factory() #cache.clear() return HttpResponseRedirect( reverse("modeltranslation:view_all_url", args=(language, "all"))) return HttpResponseRedirect(reverse("modeltranslation:admin_url"))
def import_translations(request, language): """ Import translations froma PO file. Please take note that this PO file MUST be generated with this application because translation comments in the file are used as translation ids. """ def _import_po_file(uploadedfile, lang): lines = [] for line in uploadedfile: lines.append(line) num_lines = len(lines) prog_ctxt = re.compile(r"msgctxt\s+\"(?P<id>\d+)--(?P<module>(\.\w)+)--(?P<model>\w+)--(?P<object_id>\d+)--(?P<field>\w+)\"") prog_msgid = re.compile(r"msgid\s+\"(?P<source_text>.+)\"$") prog_msgstr = re.compile(r"msgstr\s+(?P<trans>.+)") i = 0 while i < num_lines: line = lines[i] result = prog_ctxt.match(line) if result: id = result.group("id") is_fuzzy = (lines[i-1] == "#, fuzzy\n") source_text = lines[i+1] translation_line = lines[i+2] # Traducción g = prog_msgstr.match(translation_line) if g is None: i += 1 continue translation = g.group("trans").replace("msgstr","")[1:-1].replace("\\\"","\"").replace('\\\'','\'') # Get translation from a translation id try: field_trans = FieldTranslation.objects.get(id=id) except FieldTranslation.DoesNotExist: source_text = source_text.replace("msgid","")[1:-1].replace("\\\"","\"").replace('\\\'','\'') source_md5 = hashlib.md5(source_text.encode("utf-8")).hexdigest() field_trans = FieldTranslation( module=result.group("module"), model=result.group("model"), object_id=result.group("object_id"), field=result.group("field"), lang=lang, source_text=source_text, source_md5=source_md5 ) # Sets translation and is_fuzzy attribute field_trans.translation = translation field_trans.is_fuzzy = is_fuzzy field_trans.save() i += 4 i += 1 # Delete orphan translations FieldTranslation.delete_orphan_translations() if request.method != "POST": return HttpResponseRedirect(reverse("modeltranslation:admin_url")) form = ImportTranslationsForm(request.POST, request.FILES) if form.is_valid(): _import_po_file(request.FILES['file'], language) return HttpResponseRedirect(reverse("modeltranslation:view_all_url",args=(language,"all"))) return HttpResponseRedirect(reverse("modeltranslation:admin_url"))
def import_translations(request, language): """ Importa las traducciones a partir de un archivo PO. Ten en cuenta que el archivo PO ha de ser generado desde esta aplicación, de forma que los comentarios sirvan como id de traducción (lo metemos nosotros en la exportación). """ def _import_po_file(uploadedfile, lang): lines = [] for line in uploadedfile: lines.append(line) num_lines = len(lines) prog_ctxt = re.compile(r"msgctxt\s+\"(?P<id>\d+)--(?P<model>\w+)--(?P<object_id>\d+)--(?P<field>\w+)\"") prog_msgid = re.compile(r"msgid\s+\"(?P<source_text>.+)\"$") prog_msgstr = re.compile(r"msgstr\s+(?P<trans>.+)") i = 0 while i < num_lines: line = lines[i] result = prog_ctxt.match(line) if result: id = result.group("id") is_fuzzy = (lines[i-1] == "#, fuzzy\n") source_text = lines[i+1] translation_line = lines[i+2] # Traducción g = prog_msgstr.match(translation_line) if g is None: i += 1 continue translation = g.group("trans").replace("msgstr","")[1:-1].replace("\\\"","\"").replace('\\\'','\'') # Obtención de la traducción a partir del id try: field_trans = FieldTranslation.objects.get(id=id) except FieldTranslation.DoesNotExist: source_text = source_text.replace("msgid","")[1:-1].replace("\\\"","\"").replace('\\\'','\'') source_md5 = hashlib.md5(source_text.encode("utf-8")).hexdigest() field_trans = FieldTranslation(model=result.group("model"), object_id=result.group("object_id"), field=result.group("field"), lang=lang, source_text=source_text, source_md5=source_md5) # Establecemos la traducción y si es fuzzy field_trans.translation = translation field_trans.is_fuzzy = is_fuzzy field_trans.save() #print translation #print is_fuzzy i += 4 i += 1 # Elimina traducciones que no estén asociadas a ningún objeto FieldTranslation.delete_orphan_translations() # Acceso obligatoriamente por POST if request.method != "POST": return HttpResponseRedirect(reverse("modeltranslation:admin_url")) form = ImportTranslationsForm(request.POST, request.FILES) if form.is_valid(): _import_po_file(request.FILES['file'], language) #cache = TransCache.factory() #cache.clear() return HttpResponseRedirect(reverse("modeltranslation:view_all_url",args=(language,"all"))) return HttpResponseRedirect(reverse("modeltranslation:admin_url"))