Login

Changing the locale temporary

Author:
mathijs
Posted:
April 11, 2009
Language:
Python
Version:
1.0
Score:
3 (after 3 ratings)

This piece of code allows the quickly set the locale to a different language. This can be used for instance in cron jobs to send emails to users in their specific language.

This is pretty rough code, it be better to create an object, having two functions: set_locale and reset_locale. set_locale would than contain steps 1 to 4 (and return the request object on succes), reset_locale would be step 6

Enjoy!

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
from django.utils.translation import check_for_language, activate, deactivate, to_locale, get_language, ugettext as _
from django.http import HttpRequest
from django.template.loader import render_to_string
from django.template import RequestContext
from django.contrib.sessions.middleware import SessionMiddleware

# 1. Getting the current language: (if any)
cur_locale = to_locale(get_language())
# 2. create a request (& optionally add session middleware)
request = HttpRequest()
SessionMiddleware().process_request(request)
# 3. activate the temporary language: this loads the translation files
target_language = "nl" # this could be a function call, loaded from a UserProfile, ...
if check_for_language(target_language):
	activate(target_language)
locale = to_locale(get_language())
# 4. set the language code in the request (& optionally session)
request.LANGUAGE_CODE = locale
request.session['django_language'] = locale
# 5. example rendering of content:
msg_dict = { 'title': _('This is the title and will be translated'), 'body': _('Message body') }
rendered = render_to_string("some_template.html",  msg_dict, RequestContext(request));
# 6. reset back to the old locale:
deactivate()

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 3 months ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 3 months, 1 week ago
  3. Serializer factory with Django Rest Framework by julio 10 months, 1 week ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 10 months, 3 weeks ago
  5. Help text hyperlinks by sa2812 11 months, 3 weeks ago

Comments

Please login first before commenting.