Inside a Django view, I create a subject like that:
subject = _(u"%(user)s has posted a comment") % { 'user': user }
Then I pass this subject to a function, which handles email notifications:
send_notifications(request, subject, url)
In send_notifications, I iterate over all subscriptions and send emails. However, each user can have a different language, so I activate the user’s language dynamically via Django’s activate:
def send_notifications(request, subject, url):
from django.utils.translation import activate
for 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 the correct language of each user. However, the subject is passed as an evaluated and translated string to send_notifications and thus, is not translated.
I played around with lazy translations and lambda functions as parameters, but without success. Any help appreciated 🙂
Instead of passing the translated subject, just pass it non translated:
If you’re not going to personalize the contents per user, then you might as well limit the number of renderings because that’s a little confusing:
As such, it is much more obvious that you’re not going to render emails per usage.
This slight rewrite should make you doubt about the original choice of a couple of names (locals, notification_template).
The above sample code is barely an “educated guess” and you should double check it and make sure you understand everything before you paste it.