def handle(self, *args, **options): # set the locale right, to get the dates represented correctly translation.activate(settings.LANGUAGE_CODE) offeneLeistungen = (models.Leistung.objects. filter( erstellt__lte=datetime.date.today()-datetime.timedelta(days=7)). exclude( status=models.Leistung.ACK). exclude( status=models.Leistung.NEG) ) print offeneLeistungen kontakte = set([l.aufgabe.kontakt() for l in offeneLeistungen]) print kontakte for k in kontakte: mail.send( [k.email], # to address template="leistungReminder", ) call_command('send_queued_mail') translation.deactivate()
def process_response(self, request, response): # First set the default language, this will be used if there is none # in the path default_language = getattr(request, 'default_language', '') if default_language: translation.activate(default_language) language = translation.get_language() if (response.status_code == 404 and not translation.get_language_from_path(request.path_info) and self.is_language_prefix_patterns_used(request)): urlconf = getattr(request, 'urlconf', None) language_path = '/%s%s' % (language, request.path_info) if settings.APPEND_SLASH and not language_path.endswith('/'): language_path += '/' if is_valid_path(language_path, urlconf): language_url = "%s://%s/%s%s" % ( request.is_secure() and 'https' or 'http', request.get_host(), language, request.get_full_path()) return HttpResponseRedirect(language_url) translation.deactivate() patch_vary_headers(response, ('Accept-Language',)) if 'Content-Language' not in response: response['Content-Language'] = language return response
def run(self, submission, template_code): logger.info('SendEmailFromTemplate:%d template %s' % ( submission.id, template_code )) try: translation.activate(submission.submission_language) letter = LetterTemplate.objects.language().get(code=template_code) email = EmailMessage( letter.subject, letter.text % {'name': submission.applicant}, '*****@*****.**', [submission.applicant_email], list(settings.MAIL_BCC_LIST), headers = {'Reply-To': '*****@*****.**'} ) email.send() except: logger.info('SendEmailFromTemplate:%d template %s exception' % ( submission.id, template_code )) raise finally: translation.deactivate() logger.info('SendEmailFromTemplate:%d template %s done' % ( submission.id, template_code ))
def setUp(self): # There are two ways of deactivating translation: # 1. Using a custom test_runner that set settings.USE_I18N to False # 2. Monkey patching the following function translation.real_activate = trans_null.activate translation.real_ugettext = trans_null.ugettext translation.deactivate()
def items(self): from www.urls import i18n_urlpatterns items = [] init_lang = get_language() deactivate() for pattern in i18n_urlpatterns: if hasattr(pattern, 'url_patterns'): for app in pattern.url_patterns: if hasattr(app, 'url_patterns'): for url in app.url_patterns: if not url.name: continue try: base = reverse(url.name) except: continue alternates = [] for lang, lang_name in settings.LANGUAGES: activate(lang) alternate = reverse(url.name) deactivate() if alternate not in alternates: alternates.append((lang, alternate)) items.append((base, tuple(alternates))) activate(init_lang) return items
def handle(self, *args, **options): contact_email = getattr(settings, 'EMAIL_CONTACT_ADDRESS', None) if contact_email is None: raise ImproperlyConfigured('EMAIL_CONTACT_ADDRESS must be configured') today = timezone.now().date() expiration_days = (30, 15, 7) expiration_dates = [today - timezone.timedelta(days=d) for d in expiration_days] expiration_dates += [today] filter_arg = None for d in expiration_dates: since = self._make_date_lookup_arg(d) until = self._make_date_lookup_arg(d + timezone.timedelta(days=1)) if filter_arg is None: filter_arg = Q(valid_until__gte=since, valid_until__lt=until) else: filter_arg |= Q(valid_until__gte=since, valid_until__lt=until) if settings.USE_I18N: translation.activate(settings.LANGUAGE_CODE) for payment in Payment.objects.filter(filter_arg): last_payment = payment.member.get_last_payment() if last_payment: last_payment_date = last_payment.valid_until.date() status = [last_payment_date > d for d in expiration_dates] already_renewed = all(status) # skip to send notification if already renewed if already_renewed: continue valid_until_date = payment.valid_until.date() context = { 'contact_email': contact_email, 'member': payment.member, 'url': '%s%s' % (Site.objects.get_current().domain, reverse('payment', args=[payment.member.pk])), } if valid_until_date == today: context['date'] = today subject = '[Associação Python Brasil] Anuidade vencida' message = render_to_string('payment/valid_until_today_email.txt', context) else: date_diff = today - valid_until_date context['days'] = date_diff.days subject = '[Associação Python Brasil] Aviso de renovação' message = render_to_string('payment/valid_until_email.txt', context) send_mail(subject, message, contact_email, [payment.member.user.email], fail_silently=False) if settings.USE_I18N: translation.deactivate()
def run(self, submission): logger.info('SendSubmissionEmail for submission %s' % ( submission.id )) try: translation.activate(submission.submission_language) email = EmailMessage( 'Cinema Perpetuum Mobile 2013', self.get_email_message(submission), '*****@*****.**', [submission.applicant_email], list(settings.MAIL_BCC_LIST), headers = {'Reply-To': '*****@*****.**'}) email.attach( 'cpm2013.pdf', self.create_pdf(submission), 'application/pdf' ) email.send() except: logger.exception('') raise finally: translation.deactivate() try: submission = Submission.objects.get(pk=submission.pk) except Submission.DoesNotExist: logger.exception('Failed to update "email sent" status') else: submission.comment_email_sent = True submission.save()
def do_send_mail(subject, recipients, ctx, template, blacklist=()): if recipients: lang_to_email = defaultdict(set) if len(recipients) == 1: recipient = User.objects.select_related("profile__language").get(id=recipients.pop()) if not recipient.is_active: return if not recipient.email or recipient.email in blacklist: return lang_to_email[recipient.profile.language].add(recipient.email) else: qs = UserProfile.objects.filter(user__in=recipients, user__is_active=True).exclude(user__email="") for lang, email in qs.values_list("language", "user__email"): if email not in blacklist: lang_to_email[lang].add(email) if not lang_to_email: return ctx = unserialize(ctx) ctx["site"] = Site.objects.get_current() for lang, emails in lang_to_email.iteritems(): translation.activate(lang) html_content = render_to_string(template + ".html", ctx) message = _(render_to_string(template + ".txt", ctx)) subj_translation = _(subject) msg = EmailMultiAlternatives(subj_translation, message.strip(), settings.EMAIL_OPENPLM, bcc=emails) msg.attach_alternative(html_content, "text/html") msg.send(fail_silently=getattr(settings, "EMAIL_FAIL_SILENTLY", True)) if lang_to_email: translation.deactivate()
def test_default_language_duplicate_tags(sample_category, testing_user, test_resource): """ Duplicate tags should not be added based on duplicate name across current language to default This should result in no errors """ t = Tag.tags.create( name="My Fun Test", category=sample_category, create_user=testing_user, update_user=testing_user, ) tag_text = "My Fun Test" resource_add_free_text_tags(test_resource, tag_text, testing_user, t.category.slug) assert Tag.tags.all().count() == 1 translation.activate("es") resource_add_free_text_tags(test_resource, tag_text, testing_user, t.category.slug) assert Tag.tags.all().count() == 1 Tag.tags.all().delete() translation.deactivate()
def set_language(request): next = request.REQUEST.get("next", None) if not next: next = "/" url = urlparse(next) try: r = resolve(url.path) except: next = "/" response = http.HttpResponseRedirect(next) lang_code = request.GET.get("language", None) if lang_code and check_for_language(lang_code): translation.activate(lang_code) try: next = reverse("%s" % r.url_name, args=r.args, kwargs=r.kwargs) except: pass else: response = http.HttpResponseRedirect(next) translation.deactivate() if hasattr(request, "session"): request.session["django_language"] = lang_code else: response.set_cookie(settings.LANGUAGE_COOKIE_NAME, lang_code) return response
def send_keepuptodate(org,msg,to=settings.CONTACT_EMAIL, language='en'): import datetime from django.utils import translation translation.activate(language) message = GeoMail() message.to = to message.subject = "[GeoRemindMe] Keep up to date" message.body = _(""" %(date)s \n %(username)s \n %(message)s """) % { 'date': str(datetime.datetime.now()), 'username': org, 'message': msg } message.html = _(""" <html><head></head><body> %(date)s<br/>%(username)s<br/>%(message)s" </body></html> """) % { 'date': str(datetime.datetime.now()), 'username': org, 'message': msg } translation.deactivate() message.push()
def process_response(self, request, response): language = translation.get_language() if self.use_redirects: kwargs = {} if django_root_version == 16: kwargs['supported'] = self._supported_languages language_from_path = translation.get_language_from_path( request.path_info, **kwargs) if (response.status_code == 404 and not language_from_path and self.is_language_prefix_patterns_used() and language != self.default_lang): urlconf = getattr(request, 'urlconf', None) language_path = '/%s%s' % (language, request.path_info) path_valid = is_valid_path(language_path, urlconf) if (not path_valid and settings.APPEND_SLASH and not language_path.endswith('/')): path_valid = is_valid_path("%s/" % language_path, urlconf) if path_valid: language_url = "%s://%s/%s%s" % ( 'https' if request.is_secure() else 'http', request.get_host(), language, request.get_full_path()) return HttpResponseRedirect(language_url) if not (self.is_language_prefix_patterns_used() and language_from_path): patch_vary_headers(response, ('Accept-Language',)) if django_root_version < 16: translation.deactivate() if 'Content-Language' not in response: response['Content-Language'] = language return response
def process_response(self, request, response): patch_vary_headers(response, ("Accept-Language",)) translation.deactivate() if response.status_code == 200 and not request.path.startswith(settings.MEDIA_URL) and response._headers['content-type'][1].split(';')[0] == "text/html": response.content = SUB.sub(ur'<a\1href="/%s/\3"\4>' % request.LANGUAGE_CODE, response.content.decode('utf-8')) response.content = SUB2.sub(ur'<form\1action="/%s/\3"\4>' % request.LANGUAGE_CODE, response.content.decode('utf-8')) return response
def process_response(self, request, response): language = translation.get_language() if (response.status_code == 404 and not translation.get_language_from_path(request.path_info) and self.is_language_prefix_patterns_used()): urlconf = getattr(request, 'urlconf', None) language_path = '/%s%s' % (language, request.path_info) path_valid = is_valid_path(language_path, urlconf) if (not path_valid and settings.APPEND_SLASH and not language_path.endswith('/')): path_valid = is_valid_path("%s/" % language_path, urlconf) if path_valid: path = request.get_full_path() script_mount = request.META.get("SCRIPT_NAME", "") if path.startswith(script_mount): path = path.replace(script_mount, ("%s/%s" % (script_mount, language)), 1) language_url = "%s://%s%s" % ( request.is_secure() and 'https' or 'http', request.get_host(), path) return HttpResponseRedirect(language_url) translation.deactivate() patch_vary_headers(response, ('Accept-Language',)) if 'Content-Language' not in response: response['Content-Language'] = language return response
def setup_test_environment(debug=None): """ Perform global pre-test setup, such as installing the instrumented template renderer and setting the email backend to the locmem email backend. """ if hasattr(_TestState, 'saved_data'): # Executing this function twice would overwrite the saved values. raise RuntimeError( "setup_test_environment() was already called and can't be called " "again without first calling teardown_test_environment()." ) if debug is None: debug = settings.DEBUG saved_data = SimpleNamespace() _TestState.saved_data = saved_data saved_data.allowed_hosts = settings.ALLOWED_HOSTS # Add the default host of the test client. settings.ALLOWED_HOSTS = list(settings.ALLOWED_HOSTS) + ['testserver'] saved_data.debug = settings.DEBUG settings.DEBUG = debug saved_data.email_backend = settings.EMAIL_BACKEND settings.EMAIL_BACKEND = 'django.core.mail.backends.locmem.EmailBackend' saved_data.template_render = Template._render Template._render = instrumented_test_render mail.outbox = [] deactivate()
def test_localize_templatetag_and_filter(self): """ Tests the {% localize %} templatetag """ context = Context({"value": 3.14}) template1 = Template( "{% load l10n %}{% localize %}{{ value }}{% endlocalize %};{% localize on %}{{ value }}{% endlocalize %}" ) template2 = Template("{% load l10n %}{{ value }};{% localize off %}{{ value }};{% endlocalize %}{{ value }}") template3 = Template("{% load l10n %}{{ value }};{{ value|unlocalize }}") template4 = Template("{% load l10n %}{{ value }};{{ value|localize }}") output1 = "3,14;3,14" output2 = "3,14;3.14;3,14" output3 = "3,14;3.14" output4 = "3.14;3,14" old_localize = settings.USE_L10N try: activate("de") settings.USE_L10N = False self.assertEqual(template1.render(context), output1) self.assertEqual(template4.render(context), output4) settings.USE_L10N = True self.assertEqual(template1.render(context), output1) self.assertEqual(template2.render(context), output2) self.assertEqual(template3.render(context), output3) finally: deactivate() settings.USE_L10N = old_localize
def test_localized_input(self): """ Tests if form input is correctly localized """ settings.USE_L10N = True activate("de-at") try: form6 = CompanyForm( { "name": u"acme", "date_added": datetime.datetime(2009, 12, 31, 6, 0, 0), "cents_payed": decimal.Decimal("59.47"), "products_delivered": 12000, } ) self.assertEqual(True, form6.is_valid()) self.assertEqual( form6.as_ul(), u'<li><label for="id_name">Name:</label> <input id="id_name" type="text" name="name" value="acme" maxlength="50" /></li>\n<li><label for="id_date_added">Date added:</label> <input type="text" name="date_added" value="31.12.2009 06:00:00" id="id_date_added" /></li>\n<li><label for="id_cents_payed">Cents payed:</label> <input type="text" name="cents_payed" value="59,47" id="id_cents_payed" /></li>\n<li><label for="id_products_delivered">Products delivered:</label> <input type="text" name="products_delivered" value="12000" id="id_products_delivered" /></li>', ) self.assertEqual(localize_input(datetime.datetime(2009, 12, 31, 6, 0, 0)), "31.12.2009 06:00:00") self.assertEqual(datetime.datetime(2009, 12, 31, 6, 0, 0), form6.cleaned_data["date_added"]) settings.USE_THOUSAND_SEPARATOR = True self.assert_(u"12.000" in form6.as_ul()) finally: deactivate()
def tearDown(self): settings.CACHE_MIDDLEWARE_SECONDS = self.orig_cache_middleware_seconds settings.CACHE_MIDDLEWARE_KEY_PREFIX = self.orig_cache_middleware_key_prefix settings.CACHE_BACKEND = self.orig_cache_backend settings.USE_I18N = self.orig_use_i18n settings.LANGUAGES = self.orig_languages translation.deactivate()
def test_multilang(self): translation.activate('en') self._send_mail( 'mail_templated_test/multilang.tpl', {'name': 'User'}, '*****@*****.**', ['*****@*****.**'], 'Hello User', 'User, this is a plain text message.') translation.deactivate()
def create(cls, order, invoice_type): language_code = get_user_language(order.user) if language_code is not None: translation.activate(language_code) try: billing_info = BillingInfo.objects.get(user=order.user) except BillingInfo.DoesNotExist: return day = date.today() pday = order.completed if invoice_type == Invoice.INVOICE_TYPES['PROFORMA']: pday = day + timedelta(days=14) invoice = cls(issued=day, selling_date=order.completed, payment_date=pday) # FIXME: 14 - this should set accordingly to ORDER_TIMEOUT in days invoice.type = invoice_type invoice.copy_from_order(order) invoice.set_issuer_invoice_data() invoice.set_buyer_invoice_data(billing_info) invoice.clean() invoice.save() if language_code is not None: translation.deactivate()
def send_remind_pass_mail(to=None, remind_code=None, language='en'): def generate_remind_pass_link(to, remind_code): url = _('<a href="%s">Password reminder link</a>') % generate_remind_pass_url(to, remind_code) return url def generate_remind_pass_url(to, confirm_code): import os host = os.environ['HTTP_HOST'] url = 'http://%s/remind/%s/%s' % (host, base64.encodestring(to), remind_code) return url """ Send registration mail confirmation """ if to is None or remind_code is None: raise ValueError() translation.activate(language) message = GeoMail() message.sender = '*****@*****.**' message.to = to message.subject = _("Set a new password at GeoRemindMe") message.html = _("""Set a new password at GeoRemindMe %(link)s If you don't see the link, copy and paste this url: %(url)s """) % { 'link': generate_remind_pass_link(to, remind_code), 'url': generate_remind_pass_url(to, remind_code) } translation.deactivate() message.push()
def test_localized_filesizeformat(self): from django.utils.translation import activate, deactivate old_localize = settings.USE_L10N try: activate('de') settings.USE_L10N = True self.assertEqual(filesizeformat(1023), u'1023 Bytes') self.assertEqual(filesizeformat(1024), u'1,0 KB') self.assertEqual(filesizeformat(10*1024), u'10,0 KB') self.assertEqual(filesizeformat(1024*1024-1), u'1024,0 KB') self.assertEqual(filesizeformat(1024*1024), u'1,0 MB') self.assertEqual(filesizeformat(1024*1024*50), u'50,0 MB') self.assertEqual(filesizeformat(1024*1024*1024-1), u'1024,0 MB') self.assertEqual(filesizeformat(1024*1024*1024), u'1,0 GB') self.assertEqual(filesizeformat(1024*1024*1024*1024), u'1,0 TB') self.assertEqual(filesizeformat(1024*1024*1024*1024*1024), u'1,0 PB') self.assertEqual(filesizeformat(1024*1024*1024*1024*1024*2000), u'2000,0 PB') self.assertEqual(filesizeformat(complex(1,-1)), u'0 Bytes') self.assertEqual(filesizeformat(""), u'0 Bytes') self.assertEqual(filesizeformat(u"\N{GREEK SMALL LETTER ALPHA}"), u'0 Bytes') finally: deactivate() settings.USE_L10N = old_localize
def setup_test_environment(debug=None): """ Perform global pre-test setup, such as installing the instrumented template renderer and setting the email backend to the locmem email backend. """ if hasattr(_SavedSettings, 'debug'): # Executing this function twice would overwrite the saved values. raise RuntimeError( "setup_test_environment() was already called and can't be called " "again without first calling teardown_test_environment()." ) if debug is None: debug = settings.DEBUG _SavedSettings.debug = settings.DEBUG settings.DEBUG = debug Template._original_render = Template._render Template._render = instrumented_test_render # Storing previous values in the settings module itself is problematic. # Store them in arbitrary (but related) modules instead. See #20636. mail._original_email_backend = settings.EMAIL_BACKEND settings.EMAIL_BACKEND = 'django.core.mail.backends.locmem.EmailBackend' request._original_allowed_hosts = settings.ALLOWED_HOSTS # Add the default host of the test client. settings.ALLOWED_HOSTS = settings.ALLOWED_HOSTS + ['testserver'] mail.outbox = [] deactivate()
def test_localized_input(self): """ Tests if form input is correctly localized """ settings.USE_L10N = True activate('de-at') try: form6 = CompanyForm({ 'name': u'acme', 'date_added': datetime.datetime(2009, 12, 31, 6, 0, 0), 'cents_payed': decimal.Decimal('59.47'), 'products_delivered': 12000, }) self.assertEqual(True, form6.is_valid()) self.assertEqual( form6.as_ul(), u'<li><label for="id_name">Name:</label> <input id="id_name" type="text" name="name" value="acme" maxlength="50" /></li>\n<li><label for="id_date_added">Date added:</label> <input type="text" name="date_added" value="31.12.2009 06:00:00" id="id_date_added" /></li>\n<li><label for="id_cents_payed">Cents payed:</label> <input type="text" name="cents_payed" value="59,47" id="id_cents_payed" /></li>\n<li><label for="id_products_delivered">Products delivered:</label> <input type="text" name="products_delivered" value="12000" id="id_products_delivered" /></li>' ) self.assertEqual(localize_input(datetime.datetime(2009, 12, 31, 6, 0, 0)), '31.12.2009 06:00:00') self.assertEqual(datetime.datetime(2009, 12, 31, 6, 0, 0), form6.cleaned_data['date_added']) settings.USE_THOUSAND_SEPARATOR = True # Checking for the localized "products_delivered" field self.assert_(u'<input type="text" name="products_delivered" value="12.000" id="id_products_delivered" />' in form6.as_ul()) finally: deactivate()
def handle_noargs(self, **options): remind_window = timedelta(hours=settings.EVENT_REMINDER_WINDOW) remind_pause = timedelta(hours=settings.EVENT_REMINDER_PAUSE) now = datetime.now() events = Event.objects.select_related( ).filter(date__gte = now ).filter(date__lte = now + remind_window + remind_pause ).exclude(cron__gte = now - remind_pause) events_in_remind_window = False for event in events: if event.date <= now + remind_window: events_in_remind_window = True if event.all_tasks_satisfied: events = events.exclude(id = event.id) if events.count() > 0 and events_in_remind_window: translation.activate(settings.LANGUAGE_CODE) text_plain = loader.render_to_string("email/open_tasks.html", {'events': events, 'site_url': settings.SITE_URL,}) text_html = loader.render_to_string("email/open_tasks_html.html", {'events': events, 'site_url': settings.SITE_URL,}) mail = EmailMultiAlternatives( subject = settings.EVENT_REMINDER_SUBJECT, body = text_plain, from_email = settings.EVENT_REMINDER_FROM, to = settings.EVENT_REMINDER_ADDRESSBOOK, headers = {'From': settings.EVENT_REMINDER_FROM }, ) mail.attach_alternative(text_html, "text/html") mail.send() for event in events: event.cron = datetime.now() event.save() translation.deactivate()
def handle_noargs(self, **options): translation.activate('fr') logging.debug('Command in progress') week_limit = Week.withdate(Week.thisweek().day(settings.VALIDATING_DAY_OF_WEEK) + relativedelta(days=settings.DELAY_BETWEEN_DEFINITON_N_DELIVERY)) # first changed the status of expired deliveries deliveries_canceled = models.Delivery.objects.filter(date__lt=week_limit, status='w', subscription__enabled=True) for delivery in deliveries_canceled: delivery.status = 'e' delivery.save() logging.debug('delivery %d expired' % delivery.id) # secondly, get all the deliveries with a date higher or equal to J+9 and lesser than J+9+7 with a waiting status and a subscription which accepts direct debit. deliveries = models.Delivery.objects.filter(date__gte=week_limit, date__lt=week_limit+1, status='w', subscription__direct_debit=True, subscription__enabled=True) for delivery in deliveries: delivery.status = 'p' try: delivery.save() except ValueError as e: logging.debug('delivery %d not payed' % delivery.id) else: logging.debug('delivery %d payed' % delivery.id) translation.deactivate()
def send_notification_suggestion_summary(to, suggestions, language='en'): if to is None: raise ValueError() translation.activate(language) message = GeoMail() message.to = to message.subject = _(u"Resumen de la actividad en tus sugerencias - GeoRemindMe!") message.body = _(u""" Aquí te dejamos un resumen de los comentarios, valoraciones, etc que han recibido tus sugerencias a lo largo de la semana\n %(suggestion)s\n \n Si quieres cambiar la configuración de tus notificaciones, puedes hacerlo a través de tu perfil en www.georemindme.com\n, y sino...¡hasta la semana que viene!\n El equipo de GeoRemindMe! """) % { 'suggestion': suggestions, } message.html = _(u""" <html><head></head><body> <p> Aquí te dejamos un resumen de los comentarios, valoraciones, etc que han recibido tus sugerencias a lo largo de la semana<br> %(suggestion)s </p> <p> Si quieres cambiar la configuración de tus notificaciones, puedes hacerlo a través de tu perfil en www.georemindme.com\n, y sino...¡hasta la semana que viene!<br> El equipo de GeoRemindMe! </p> </body></html> """) % { 'suggestion': suggestions, } translation.deactivate() message.push()
def testAgendaList(self): translation.activate(settings.LANGUAGE_CODE) # test anonymous user res = self.client.get(reverse("agenda-list")) self.assertEqual(res.status_code, 200) self.assertTemplateUsed(res, "agendas/agenda_list.html") object_list = res.context["object_list"] self.assertEqual(map(just_id, object_list), [self.agenda_1.id, self.agenda_2.id]) # test logged in user 1 self.assertTrue(self.client.login(username="******", password="******")) res = self.client.get(reverse("agenda-list")) self.assertEqual(res.status_code, 200) self.assertTemplateUsed(res, "agendas/agenda_list.html") object_list = res.context["object_list"] self.assertEqual(map(just_id, object_list), [self.agenda_1.id, self.agenda_2.id]) # test logged in user 2 self.assertTrue(self.client.login(username="******", password="******")) res = self.client.get(reverse("agenda-list")) self.assertEqual(res.status_code, 200) self.assertTemplateUsed(res, "agendas/agenda_list.html") object_list = res.context["object_list"] self.assertEqual(map(just_id, object_list), [self.agenda_1.id, self.agenda_2.id, self.agenda_3.id]) # test logged in as superuser self.assertTrue(self.client.login(username="******", password="******")) res = self.client.get(reverse("agenda-list")) self.assertEqual(res.status_code, 200) self.assertTemplateUsed(res, "agendas/agenda_list.html") object_list = res.context["object_list"] self.assertEqual(map(just_id, object_list), [self.agenda_1.id, self.agenda_2.id, self.agenda_3.id]) translation.deactivate()
def send_digest(user, activity, activities_list, date_digest): # Render digest mail SITE_URL = "https://{0}".format(Site.objects.get_current().domain) # Activate the last language used by the user activate(user.last_used_language) # if user.is_pro(): # display_url = lambda: "{0}{1}".format(SITE_URL, activity.report.get_absolute_url_pro()) # unsubscribe_url = lambda: "{0}{1}".format(SITE_URL, reverse("unsubscribe_pro", args=[activity.report.id])) # else: # display_url = lambda: "{0}{1}".format(SITE_URL, activity.report.get_absolute_url()) # unsubscribe_url = lambda: "{0}{1}?citizen_email={2}".format(SITE_URL, reverse("unsubscribe", args=[activity.report.id]), user.email) digests_subscriptions = render_to_string("emails/digest.html", {'site_url': SITE_URL, 'user_is_pro': user.is_pro(), 'activities_list': activities_list, 'date_digest': date_digest}) logger.info('Sending digest to %s' % user.email) title = list() trickystuff = get_language() for l in settings.LANGUAGES: activate(l[0]) title.append(_("Digest of the day on Fix My Street")) deactivate() activate(trickystuff) subject = u" / ".join(title) msg = EmailMultiAlternatives(subject, digests_subscriptions, settings.DEFAULT_FROM_EMAIL, (user.email,)) msg.attach_alternative(digests_subscriptions, "text/html") msg.send() deactivate()
def test_dir_rtl(self): """Make sure dir attr is set to 'rtl' for RTL language.""" translation.activate('he') self.request.LANGUAGE_CODE = 'he' html = jingo.render_to_string(self.request, self.template) eq_('rtl', pq(html)('html').attr['dir']) translation.deactivate()
def send_template_email(recipients, title_template, body_template, context, language): """Sends e-mail using templating system""" send_emails = getattr(settings, 'SEND_PLANS_EMAILS', True) if not send_emails: return site_name = getattr(settings, 'SITE_NAME', 'Please define settings.SITE_NAME') domain = getattr(settings, 'SITE_URL', None) if domain is None: Site = cache.get_model('sites', 'Site') current_site = Site.objects.get_current() site_name = current_site.name domain = current_site.domain context.update({'site_name': site_name, 'site_domain': domain}) if language is not None: translation.activate(language) mail_title_template = loader.get_template(title_template) mail_body_template = loader.get_template(body_template) title = mail_title_template.render(context) body = mail_body_template.render(context) try: email_from = getattr(settings, 'DEFAULT_FROM_EMAIL') except AttributeError: raise ImproperlyConfigured( 'DEFAULT_FROM_EMAIL setting needed for sending e-mails') mail.send_mail(title, body, email_from, recipients) if language is not None: translation.deactivate() email_logger.info(u"Email (%s) sent to %s\nTitle: %s\n%s\n\n" % (language, recipients, title, body))
def send_invoice_by_email(self): language_code = get_user_language(self.user) if language_code is not None: translation.activate(language_code) mail_context = { 'user': self.user, 'invoice_type': self.get_type_display(), 'invoice_number': self.get_full_number(), 'order': self.order.id, 'url': self.get_absolute_url(), } if language_code is not None: translation.deactivate() send_template_email([self.user.email], 'mail/invoice_created_title.txt', 'mail/invoice_created_body.txt', mail_context, language_code)
def test_post(self): assert self.client.login(username='******', password='******') url = reverse('localizers.categories', kwargs=dict(locale_code='es-ES')) data = { 'form-TOTAL_FORMS': 2, 'form-INITIAL_FORMS': 2, 'form-0-id': self.cat1.id, 'form-0-name': u'Nada', 'form-1-id': self.cat2.id, 'form-1-name': u'Amigo', } res = self.client.post(url, data, follow=True) self.assertRedirects(res, url, status_code=302) doc = pq(res.content.decode('utf-8')) eq_(doc('#id_form-0-name').val(), u'Nada') eq_(doc('#id_form-1-name').val(), u'Amigo') translation.activate('es-ES') cat = Category.objects.get(pk=self.cat1.id) eq_(cat.name, u'Nada') translation.deactivate()
def process_response(self, request, response): language = getattr(request, 'update_language_cookie', False) if language: if request.user.is_authenticated() and hasattr( request.user, 'language'): language = getattr(request.user, 'language') else: language = language or request.LANGUAGE_CODE response.set_cookie(settings.LANGUAGE_COOKIE_NAME, language, max_age=settings.LANGUAGE_COOKIE_AGE, path=settings.LANGUAGE_COOKIE_PATH, domain=settings.LANGUAGE_COOKIE_DOMAIN) patch_vary_headers(response, ("Accept-Language", )) response["Content-Language"] = translation.get_language() translation.deactivate() return response
def translations_all_json(request): response_dict = defaultdict(dict) for t in SubmissionTranslation.objects.all().select_related('submission'): translation.activate(t.language) response_dict[t.submission_id][t.language] = { 'title': t.title, 'genre': t.genre, 'synopsis': t.synopsis, 'synopsis_short': t.synopsis_short, 'director': t.director, 'language': t.submission.get_language_display(), } translation.deactivate() return HttpResponse( json.dumps(response_dict, indent=2), content_type="application/json" )
def process_response(self, request, response): language = translation.get_language() if (response.status_code == 404 and not translation.get_language_from_path(request.path_info) and self.is_language_prefix_patterns_used()): urlconf = getattr(request, 'urlconf', None) language_path = '/%s%s' % (language, request.path_info) if settings.APPEND_SLASH and not language_path.endswith('/'): language_path = language_path + '/' if is_valid_path(language_path, urlconf): language_url = "%s://%s/%s%s" % ( request.is_secure() and 'https' or 'http', request.get_host(), language, request.get_full_path()) return HttpResponsePermanentRedirect(language_url) translation.deactivate() patch_vary_headers(response, ('Accept-Language',)) if 'Content-Language' not in response: response['Content-Language'] = language return response
def test_create_with_dict(self): # Set translations with a dict. strings = {'en-US': 'right language', 'de': 'wrong language'} o = TranslatedModel.objects.create(name=strings) # Make sure we get the English text since we're in en-US. trans_eq(o.name, 'right language', 'en-US') # Check that de was set. translation.activate('de') o = TranslatedModel.objects.get(id=o.id) trans_eq(o.name, 'wrong language', 'de') # We're in de scope, so we should see the de text. de = TranslatedModel.objects.create(name=strings) trans_eq(o.name, 'wrong language', 'de') # Make sure en-US was still set. translation.deactivate() o = TranslatedModel.objects.get(id=de.id) trans_eq(o.name, 'right language', 'en-US')
def handle(self, *args, **options): translation.activate(settings.DEFAULT_LOCALE) # Arguments are sender message if len(args) != 2: logger.warning(u"No message or senderID provided\n" \ u"Format is senderID \"message text\"") return False msg_sender = unicode(args[0]) msg_str = unicode(args[1]) message = Message(identity=msg_sender, \ text=msg_str, status=Message.STATUS_CREATED, \ direction=Message.DIRECTION_INCOMING) message.save() message.date = datetime.now() message.save() try: handler_func = import_path(settings.NOSMS_HANDLER) except AttributeError: message.status = Message.STATUS_ERROR message.save() logger.error(u"NO SMS_HANDLER defined while receiving SMS") except Exception as e: message.status = Message.STATUS_ERROR message.save() logger.error(u"Unable to call SMS_HANDLER with %r" % e) else: try: handler_func(message) except Exception as e: message.status = Message.STATUS_ERROR message.save() logger.error(u"SMS handler failed on %s with %r" \ % (message, e)) translation.deactivate()
def testAgendaList(self): translation.activate(settings.LANGUAGE_CODE) # test anonymous user res = self.client.get(reverse('agenda-list')) self.assertEqual(res.status_code, 200) self.assertTemplateUsed(res, 'agendas/agenda_list.html') object_list = res.context['object_list'] self.assertEqual(map(just_id, object_list), [ self.agenda_1.id, self.agenda_2.id, ]) # test logged in user 1 self.assertTrue(self.client.login(username='******', password='******')) res = self.client.get(reverse('agenda-list')) self.assertEqual(res.status_code, 200) self.assertTemplateUsed(res, 'agendas/agenda_list.html') object_list = res.context['object_list'] self.assertEqual(map(just_id, object_list), [ self.agenda_1.id, self.agenda_2.id, ]) # test logged in user 2 self.assertTrue(self.client.login(username='******', password='******')) res = self.client.get(reverse('agenda-list')) self.assertEqual(res.status_code, 200) self.assertTemplateUsed(res, 'agendas/agenda_list.html') object_list = res.context['object_list'] self.assertEqual(map(just_id, object_list), [ self.agenda_1.id, self.agenda_2.id, self.agenda_3.id]) # test logged in as superuser self.assertTrue(self.client.login(username='******', password='******')) res = self.client.get(reverse('agenda-list')) self.assertEqual(res.status_code, 200) self.assertTemplateUsed(res, 'agendas/agenda_list.html') object_list = res.context['object_list'] self.assertEqual(map(just_id, object_list), [self.agenda_1.id, self.agenda_2.id, self.agenda_3.id]) translation.deactivate()
def handle(self, *args, **options): from django.conf import settings translation.activate(settings.LANGUAGE_CODE) from django.contrib.auth import get_user_model from wiki.plugins.notifications import models from wiki.plugins.notifications.settings import ARTICLE_EDIT from wiki.models import Article from django_nyt.utils import subscribe from django_nyt.models import Settings from django.contrib.contenttypes.models import ContentType # User: Settings settings_map = {} def subscribe_to_article(article, user): if user not in settings_map: settings_map[user], __ = Settings.objects.get_or_create(user=user) return subscribe(settings_map[user], ARTICLE_EDIT, content_type=ContentType.objects.get_for_model(article), object_id=article.id) subs = 0 articles = Article.objects.all() for article in articles: if article.owner: subscription = subscribe_to_article(article, article.owner) models.ArticleSubscription.objects.get_or_create(article=article, subscription=subscription) subs += 1 for revision in article.articlerevision_set.exclude(user=article.owner).exclude(user=None).values('user').distinct(): user = get_user_model().objects.get(id=revision['user']) subs += 1 subscription = subscribe_to_article(article, user) models.ArticleSubscription.objects.get_or_create(article=article, subscription=subscription) print("Created {subs:d} subscriptions on {arts:d} articles".format( subs=subs, arts=articles.count(), )) translation.deactivate()
def send_digest(user, activity, activities_list, date_digest): # Render digest mail SITE_URL = "https://{0}".format(Site.objects.get_current().domain) # Activate the last language used by the user activate(user.last_used_language) # if user.is_pro(): # display_url = lambda: "{0}{1}".format(SITE_URL, activity.report.get_absolute_url_pro()) # unsubscribe_url = lambda: "{0}{1}".format(SITE_URL, reverse("unsubscribe_pro", args=[activity.report.id])) # else: # display_url = lambda: "{0}{1}".format(SITE_URL, activity.report.get_absolute_url()) # unsubscribe_url = lambda: "{0}{1}?citizen_email={2}".format(SITE_URL, reverse("unsubscribe", args=[activity.report.id]), user.email) digests_subscriptions = render_to_string( "emails/digest.html", { 'site_url': SITE_URL, 'user_is_pro': user.is_pro(), 'activities_list': activities_list, 'date_digest': date_digest }) logger.info('Sending digest to %s' % user.email) title = list() trickystuff = get_language() for l in settings.LANGUAGES: activate(l[0]) title.append(_("Digest of the day on Fix My Street")) deactivate() activate(trickystuff) subject = u" / ".join(title) msg = EmailMultiAlternatives(subject, digests_subscriptions, settings.DEFAULT_FROM_EMAIL, (user.email, )) msg.attach_alternative(digests_subscriptions, "text/html") msg.send() deactivate()
def handle(self, *args, **options): username = options['username'] if options['username'] else options[ 'email'].split('@')[0] name = options['name'] if options['name'] else options['email'].split( '@')[0] # parse out the course into a coursekey course = CourseKey.from_string( options['course']) if options['course'] else None form = AccountCreationForm(data={ 'username': username, 'email': options['email'], 'password': options['password'], 'name': name, }, tos_required=False) # django.utils.translation.get_language() will be used to set the new # user's preferred language. This line ensures that the result will # match this installation's default locale. Otherwise, inside a # management command, it will always return "en-us". translation.activate(settings.LANGUAGE_CODE) try: user, _, reg = _do_create_account(form) if options['staff']: user.is_staff = True user.save() reg.activate() reg.save() create_comments_service_user(user) except AccountValidationError as e: print(e.message) user = User.objects.get(email=options['email']) if course: CourseEnrollment.enroll(user, course, mode=options['mode']) translation.deactivate()
def list_congresos(self, story, congresos): translation.activate('es') for congreso in congresos: text = "" if congreso.titulo: text += u"<b>%s</b><br/>" % congreso.titulo if congreso.nombre_del_congreso: text += u"%s " % congreso.nombre_del_congreso if congreso.ciudad_de_realizacion and congreso.fecha_de_inicio: translation.activate('es') text += "(%s, %s de %s)<br/>" % ( congreso.ciudad_de_realizacion, ugettext(congreso.fecha_de_inicio.strftime("%B")), congreso.fecha_de_inicio.strftime("%Y")) elif congreso.ciudad_de_realizacion: text += "(%s)<br/>" % congreso.ciudad_de_realizacion elif congreso.fecha_de_inicio: text += "(%s)<br/>" % congreso.fecha_de_inicio if congreso.autores: text += u"%s" % congreso.autores story.append(Paragraph(text, self.style_n())) translation.deactivate()
def profile_svg(cls, profile, language): """ Plot the altimetric graph in SVG using PyGal. Most of the job done here is dedicated to preparing nice labels scales. """ ceil_elevation, floor_elevation = cls.altimetry_limits(profile) config = dict( show_legend=False, print_values=False, show_dots=False, zero=floor_elevation, value_formatter=lambda v: '%d' % v, margin=settings.ALTIMETRIC_PROFILE_FONTSIZE, width=settings.ALTIMETRIC_PROFILE_WIDTH, height=settings.ALTIMETRIC_PROFILE_HEIGHT, title_font_size=settings.ALTIMETRIC_PROFILE_FONTSIZE, label_font_size=0.8 * settings.ALTIMETRIC_PROFILE_FONTSIZE, major_label_font_size=settings.ALTIMETRIC_PROFILE_FONTSIZE, js=[]) style = LightSolarizedStyle style.background = settings.ALTIMETRIC_PROFILE_BACKGROUND style.colors = (settings.ALTIMETRIC_PROFILE_COLOR, ) style.font_family = settings.ALTIMETRIC_PROFILE_FONT line_chart = pygal.XY(fill=True, style=style, **config) if language: translation.activate(language) line_chart.x_title = _("Distance (m)") line_chart.y_title = _("Altitude (m)") line_chart.show_minor_x_labels = False line_chart.x_labels_major_count = 5 line_chart.show_minor_y_labels = False line_chart.truncate_label = 50 line_chart.range = [floor_elevation, ceil_elevation] line_chart.no_data_text = _("Altimetry data not available") translation.deactivate() line_chart.add('', [(int(v[0]), int(v[3])) for v in profile]) return line_chart.render()
def process_response(self, request, response): patch_vary_headers(response, ("Accept-Language",)) translation.deactivate() path = unicode(request.path) if not path.startswith(settings.MEDIA_URL) and \ not path.startswith(settings.ADMIN_MEDIA_PREFIX) and \ response.status_code == 200 and \ response._headers['content-type'][1].split(';')[0] == "text/html": try: decoded_response = response.content.decode('utf-8') except UnicodeDecodeError: decoded_response = response.content response.content = SUB.sub(ur'<a\1href="/%s/\3"\4>' % request.LANGUAGE_CODE, decoded_response) response.content = SUB2.sub(ur'<form\1action="/%s/\3"\4>' % request.LANGUAGE_CODE, decoded_response) if (response.status_code == 301 or response.status_code == 302 ): location = response._headers['location'] prefix = has_lang_prefix(location[1]) if not prefix and location[1].startswith("/") and \ not location[1].startswith(settings.MEDIA_URL) and \ not location[1].startswith(settings.ADMIN_MEDIA_PREFIX): response._headers['location'] = (location[0], "/%s%s" % (request.LANGUAGE_CODE, location[1])) return response
def get_context_data(self, **kwargs): lang = self.request.GET.get('lang') portal = self.request.GET.get('portal') context = super(MetaMixin, self).get_context_data(**kwargs) context['FACEBOOK_APP_ID'] = settings.FACEBOOK_APP_ID context['FACEBOOK_IMAGE'] = urljoin(self.request.GET['rando_url'], settings.FACEBOOK_IMAGE) context['FACEBOOK_IMAGE_WIDTH'] = settings.FACEBOOK_IMAGE_WIDTH context['FACEBOOK_IMAGE_HEIGHT'] = settings.FACEBOOK_IMAGE_HEIGHT translation.activate(lang) context['META_TITLE'] = _('Geotrek Rando') translation.deactivate() if portal: try: target_portal = TargetPortal.objects.get(name=portal) context['FACEBOOK_APP_ID'] = target_portal.facebook_id context['FACEBOOK_IMAGE'] = urljoin(self.request.GET['rando_url'], target_portal.facebook_image_url) context['FACEBOOK_IMAGE_WIDTH'] = target_portal.facebook_image_width context['FACEBOOK_IMAGE_HEIGHT'] = target_portal.facebook_image_height context['META_TITLE'] = getattr(target_portal, 'title_{}'.format(lang)) except TargetPortal.DoesNotExist: pass return context
def setup_test_environment(): """Perform any global pre-test setup. This involves: - Installing the instrumented test renderer - Set the email backend to the locmem email backend. - Setting the active locale to match the LANGUAGE_CODE setting. """ Template.original_render = Template._render Template._render = instrumented_test_render mail.original_SMTPConnection = mail.SMTPConnection mail.SMTPConnection = locmem.EmailBackend mail.original_email_backend = settings.EMAIL_BACKEND settings.EMAIL_BACKEND = 'django.core.mail.backends.locmem.EmailBackend' settings._original_allowed_hosts = settings.ALLOWED_HOSTS settings.ALLOWED_HOSTS = ['*'] mail.outbox = [] deactivate()
def test_localized_filesizeformat(self): from django.utils.translation import activate, deactivate old_localize = settings.USE_L10N try: activate('de') settings.USE_L10N = True self.assertEqual(filesizeformat(1023), u'1023 Bytes') self.assertEqual(filesizeformat(1024), u'1,0 KB') self.assertEqual(filesizeformat(10 * 1024), u'10,0 KB') self.assertEqual(filesizeformat(1024 * 1024 - 1), u'1024,0 KB') self.assertEqual(filesizeformat(1024 * 1024), u'1,0 MB') self.assertEqual(filesizeformat(1024 * 1024 * 50), u'50,0 MB') self.assertEqual(filesizeformat(1024 * 1024 * 1024 - 1), u'1024,0 MB') self.assertEqual(filesizeformat(1024 * 1024 * 1024), u'1,0 GB') self.assertEqual(filesizeformat(complex(1, -1)), u'0 Bytes') self.assertEqual(filesizeformat(""), u'0 Bytes') self.assertEqual(filesizeformat(u"\N{GREEK SMALL LETTER ALPHA}"), u'0 Bytes') finally: deactivate() settings.USE_L10N = old_localize
def handle(self, *args, **options): translation.activate(settings.LANGUAGE_CODE) if options['all']: delete_index_es() time.sleep(10) create_index_es() time.sleep(10) iteration = 0 for video in VIDEOS: if iteration % 1000 == 0: time.sleep(10) iteration += 1 index_es(video) elif options['video_id']: for video_id in options['video_id']: self.manage_es(video_id) else: self.stdout.write( self.style.ERROR( "****** Warning: you must give some arguments: %s ******" % self.args)) translation.deactivate()
def handle(self, *args, **options): # Activate a fixed locale, e.g. Russian translation.activate('ru') # Or you can activate the LANGUAGE_CODE # chosen in the settings: from django.conf import settings translation.activate(settings.LANGUAGE_CODE) for poll_id in options['poll_id']: try: poll = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise CommandError('Poll "%s" does not exist' % poll_id) poll.opened = False poll.save() if options['delete']: poll.delete() self.stdout.write( self.style.SUCCESS('Successfully closed poll "%s"' % poll_id)) translation.deactivate()
def test_regression_5216(self): # There was some problems with form translations in #5216 class SomeForm(Form): field_1 = CharField(max_length=10, label=ugettext_lazy('field_1')) field_2 = CharField(max_length=10, label=ugettext_lazy('field_2'), widget=TextInput(attrs={'id': 'field_2_id'})) f = SomeForm() self.assertEqual(f['field_1'].label_tag(), '<label for="id_field_1">field_1</label>') self.assertEqual(f['field_2'].label_tag(), '<label for="field_2_id">field_2</label>') # Unicode decoding problems... GENDERS = ((u'\xc5', u'En tied\xe4'), (u'\xf8', u'Mies'), (u'\xdf', u'Nainen')) class SomeForm(Form): somechoice = ChoiceField(choices=GENDERS, widget=RadioSelect(), label=u'\xc5\xf8\xdf') f = SomeForm() self.assertEqual(f.as_p(), u'<p><label for="id_somechoice_0">\xc5\xf8\xdf:</label> <ul>\n<li><label for="id_somechoice_0"><input type="radio" id="id_somechoice_0" value="\xc5" name="somechoice" /> En tied\xe4</label></li>\n<li><label for="id_somechoice_1"><input type="radio" id="id_somechoice_1" value="\xf8" name="somechoice" /> Mies</label></li>\n<li><label for="id_somechoice_2"><input type="radio" id="id_somechoice_2" value="\xdf" name="somechoice" /> Nainen</label></li>\n</ul></p>') # Testing choice validation with UTF-8 bytestrings as input (these are the # Russian abbreviations "мес." and "шт.". UNITS = (('\xd0\xbc\xd0\xb5\xd1\x81.', '\xd0\xbc\xd0\xb5\xd1\x81.'), ('\xd1\x88\xd1\x82.', '\xd1\x88\xd1\x82.')) f = ChoiceField(choices=UNITS) self.assertEqual(f.clean(u'\u0448\u0442.'), u'\u0448\u0442.') self.assertEqual(f.clean('\xd1\x88\xd1\x82.'), u'\u0448\u0442.') # Translated error messages used to be buggy. activate('ru') f = SomeForm({}) self.assertEqual(f.as_p(), u'<ul class="errorlist"><li>\u041e\u0431\u044f\u0437\u0430\u0442\u0435\u043b\u044c\u043d\u043e\u0435 \u043f\u043e\u043b\u0435.</li></ul>\n<p><label for="id_somechoice_0">\xc5\xf8\xdf:</label> <ul>\n<li><label for="id_somechoice_0"><input type="radio" id="id_somechoice_0" value="\xc5" name="somechoice" /> En tied\xe4</label></li>\n<li><label for="id_somechoice_1"><input type="radio" id="id_somechoice_1" value="\xf8" name="somechoice" /> Mies</label></li>\n<li><label for="id_somechoice_2"><input type="radio" id="id_somechoice_2" value="\xdf" name="somechoice" /> Nainen</label></li>\n</ul></p>') deactivate() # Deep copying translated text shouldn't raise an error) from django.utils.translation import gettext_lazy class CopyForm(Form): degree = IntegerField(widget=Select(choices=((1, gettext_lazy('test')),))) f = CopyForm()
def setup_test_environment(): """Perform any global pre-test setup. This involves: - Installing the instrumented test renderer - Set the email backend to the locmem email backend. - Setting the active locale to match the LANGUAGE_CODE setting. """ Template._original_render = Template._render Template._render = instrumented_test_render # Storing previous values in the settings module itself is problematic. # Store them in arbitrary (but related) modules instead. See #20636. mail._original_email_backend = settings.EMAIL_BACKEND settings.EMAIL_BACKEND = 'django.core.mail.backends.locmem.EmailBackend' request._original_allowed_hosts = settings.ALLOWED_HOSTS settings.ALLOWED_HOSTS = ['*'] mail.outbox = [] deactivate()
def handle(self, *args, **options): # process active person translation.activate(settings.LANGUAGE_CODE) applications = ['organization_network', 'organization_projects'] for app in applications: print(str(_(app))) models = apps.all_models[app] tab = " " for model_str, model in models.items(): print(tab + model_str + tab + str(_(model._meta.verbose_name))) fields = model._meta.get_fields() for field in fields: field_str = "" try: field_str += tab + tab + tab + field.attname # field_str += tab + str(field.verbose_name) field_str += tab + str(_(field.verbose_name)) except AttributeError: pass if field_str: print(field_str) translation.deactivate()
def get_context_data(self, **kwargs): lang = self.request.GET.get('lang') portal = self.request.GET.get('portal') context = super(Meta, self).get_context_data(**kwargs) translation.activate(lang) context['META_DESCRIPTION'] = _( 'Geotrek is a web app allowing you to prepare your next trekking trip !' ) translation.deactivate() if portal: try: target_portal = TargetPortal.objects.get(name=portal) context['META_DESCRIPTION'] = getattr( target_portal, 'description_{}'.format(lang)) except TargetPortal.DoesNotExist: pass if 'geotrek.trekking' in settings.INSTALLED_APPS: from geotrek.trekking.models import Trek context['treks'] = Trek.objects.existing().order_by('pk').filter( Q(**{'published_{lang}'.format(lang=lang): True}) | Q( **{ 'trek_parents__parent__published_{lang}'.format(lang=lang): True, 'trek_parents__parent__deleted': False })) if 'geotrek.tourism' in settings.INSTALLED_APPS: from geotrek.tourism.models import TouristicContent, TouristicEvent context['contents'] = TouristicContent.objects.existing().order_by( 'pk').filter(**{'published_{lang}'.format(lang=lang): True}) context['events'] = TouristicEvent.objects.existing().order_by( 'pk').filter(**{'published_{lang}'.format(lang=lang): True}) if 'geotrek.diving' in settings.INSTALLED_APPS: from geotrek.diving.models import Dive context['dives'] = Dive.objects.existing().order_by('pk').filter( **{'published_{lang}'.format(lang=lang): True}) return context
def send_notification_follower(to, follower, language='en'): if to is None or follower is None: raise ValueError() translation.activate(language) message = GeoMail() message.to = to message.subject = _( u"%s te está siguiendo ahora en Georemindme!") % follower message.body = _(u""" %(username)s te está siguiendo ahora, puedes ver su perfil en:\n %(user_profile)s\n \n Si quieres cambiar la configuración de tus notificaciones, puedes hacerlo a traves de tu perfil en www.georemindme.com\n \n Muchas gracias,\n El equipo de GeoRemindMe! """) % { 'username': follower.username, 'user_profile': follower.get_absolute_url } message.html = _(u""" <html><head></head><body> %(username)s te está siguiendo ahora, puedes ver su perfil en:<br> <a href="%(user_profile)s">%(user_profile)s</a><br> <br> Si quieres cambiar la configuración de tus notificaciones, puedes hacerlo a traves de tu perfil en <a href="http://www.georemindme.com">www.georemindme.com</a>\n <br> Muchas gracias,<br> El equipo de GeoRemindMe! </body></html> """) % { 'username': follower.username, 'user_profile': follower.get_absolute_url } translation.deactivate() message.push()
def handle_async(self, *args, **options): # set language for the translation of the messages locale = settings.LANGUAGE_CODE if not options["locale"] else options[ "locale"] translation.activate(locale) translate_labels() self.overall_error = [] filepath = self.get_filepath(options) facility = self.get_facility(options) job = get_current_job() total_rows = FacilityUser.objects.filter(facility=facility).count() with self.start_progress(total=total_rows) as progress_update: try: for row in csv_file_generator( facility, filepath, overwrite=options["overwrite"], ): progress_update(1) except (ValueError, IOError) as e: self.overall_error.append(MESSAGES[FILE_WRITE_ERROR].format(e)) raise CommandError(self.overall_error[-1]) # freeze error messages translations: self.overall_error = [str(msg) for msg in self.overall_error] if job: job.extra_metadata["overall_error"] = self.overall_error job.extra_metadata["users"] = total_rows job.extra_metadata["filename"] = ntpath.basename(filepath) job.save_meta() else: logger.info("Created csv file {} with {} lines".format( filepath, total_rows)) translation.deactivate()
def handle(self, *args, **options): translation.activate(settings.DEFAULT_LOCALE) logger.info(u"Launching NOSMS main loop") incoming = Message.incoming.filter(status=Message.STATUS_CREATED).all() if incoming.count() > 0: logger.info(u"Dispatching %d unhandled " \ u"incoming messages" % incoming.count()) for message in incoming: try: process_incoming_message(message) message.status = Message.STATUS_PROCESSED message.save() except: pass logger.info(u"Waiting for outgoing message to be sent...") while True: message = next_message() if message: logger.info(u"Sending out Message: %s" % message) try: process_outgoing_message(message) except Exception as e: logger.error(u"Unable to send %s with %r" % (message, e)) message.status = Message.STATUS_ERROR message.save() else: message.status = Message.STATUS_PROCESSED message.save() try: time.sleep(2) except KeyboardInterrupt: break translation.deactivate()
def do_send_mail(subject, recipients, ctx, template, blacklist=()): if recipients: lang_to_email = defaultdict(set) if len(recipients) == 1: recipient = User.objects.select_related("profile__language").get( id=recipients.pop()) if not recipient.is_active: return if not recipient.email or recipient.email in blacklist: return lang_to_email[recipient.profile.language].add(recipient.email) else: qs = UserProfile.objects.filter( user__in=recipients, user__is_active=True).exclude(user__email="") for lang, email in qs.values_list("language", "user__email"): if email not in blacklist: lang_to_email[lang].add(email) if not lang_to_email: return ctx = unserialize(ctx) ctx["site"] = Site.objects.get_current() for lang, emails in lang_to_email.iteritems(): translation.activate(lang) html_content = render_to_string(template + ".html", ctx) message = _(render_to_string(template + ".txt", ctx)) subj_translation = _(subject) msg = EmailMultiAlternatives(subj_translation, message.strip(), settings.EMAIL_OPENPLM, bcc=emails) msg.attach_alternative(html_content, "text/html") msg.send( fail_silently=getattr(settings, "EMAIL_FAIL_SILENTLY", True)) if lang_to_email: translation.deactivate()
def run(self, submission, template_code): logger.info('SendEmailFromTemplate:%d template %s' % (submission.id, template_code)) try: translation.activate(submission.submission_language) letter = LetterTemplate.objects.language().get(code=template_code) email = EmailMessage(letter.subject, letter.text % {'name': submission.applicant}, '*****@*****.**', [submission.applicant_email], list(settings.MAIL_BCC_LIST), headers={'Reply-To': '*****@*****.**'}) email.send() except: logger.info('SendEmailFromTemplate:%d template %s exception' % (submission.id, template_code)) raise finally: translation.deactivate() logger.info('SendEmailFromTemplate:%d template %s done' % (submission.id, template_code))
def generate_flat_topic_tree(node_cache=None, lang_code=settings.LANGUAGE_CODE): translation.activate(lang_code) categories = node_cache or get_node_cache() result = dict() # make sure that we only get the slug of child of a topic # to avoid redundancy for category_name, category in categories.iteritems(): result[category_name] = {} for node_name, node_list in category.iteritems(): node = node_list[0] relevant_data = { 'title': _(node['title']), 'path': node['path'], 'kind': node['kind'], 'available': node.get('available', True), } result[category_name][node_name] = relevant_data translation.deactivate() return result