internationalization - Pass a lazy translation string including variable to function in Django -
inside django view, create subject that:
subject = _(u"%(user)s has posted comment") % { 'user': user }
then pass subject function, handles email notifications:
send_notifications(request, subject, url)
in send_notifications, iterate on subscriptions , send emails. however, each user can have different language, activate user's language dynamically via django's activate:
def send_notifications(request, subject, url): django.utils.translation import activate s in subscription.objects.filter(url=url): activate(s.user.userprofile.lang) send_mail(subject, render_to_string('notification_email.txt', locals()), settings.server_email, [s.user.email])
the template gets rendered in correct language of each user. however, subject passed evaluated , translated string send_notifications , thus, not translated.
i played around lazy translations , lambda functions parameters, without success. appreciated :)
instead of passing translated subject, pass non translated:
subject = '%(user)s has posted comment' context = {'user': user} def send_notifications(request, subject, url, context): django.utils.translation import activate s in subscription.objects.filter(url=url): activate(s.user.userprofile.lang) send_mail(_(subject) % context, render_to_string('notification_email.txt', locals()), settings.server_email, [s.user.email])
if you're not going personalize contents per user, might limit number of renderings because that's little confusing:
# imports @ top catch import issues django.utils.translation import activate django.utils.translation import ugettext _ def send_notifications(request, url, translatable_subject, context, body_template='notification_template.txt'): previous_lang = none s in subscription.objects.filter(url=url).order_by('user__userprofile__lang'): if s.user.userprofile.lang != previous_lang: activate(s.user.userprofile.lang) subject = _(translatable_subject) % context body = render_to_string(body_template, locals()) send_mail(subject, body, settings.server_email, [s.user.email]) previous_lang = s.user.userprofile.lang
as such, more obvious you're not going render emails per usage.
this slight rewrite should make doubt original choice of couple of names (locals, notification_template).
the above sample code barely "educated guess" , should double check , make sure understand before paste it.
Comments
Post a Comment