Skip to content

Commit 5127c4e

Browse files
andyewenmaxmalysh
authored andcommitted
Improve translation notes in the FAQ. (celery#565)
Update FAQ to demonstrate `translation.override` instead of `translation.activate` for switching language inside a task. The override function is safer and simpler.
1 parent 5ab6e3c commit 5127c4e

File tree

1 file changed

+8
-13
lines changed

1 file changed

+8
-13
lines changed

FAQ

Lines changed: 8 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -5,18 +5,15 @@
55
Generating a template in a task doesn't seem to respect my i18n settings?
66
-------------------------------------------------------------------------
77

8-
**Answer**: To enable the Django translation machinery you need to activate
9-
it with a language. **Note**: Be sure to reset to the previous language when
10-
done.
8+
**Answer**: To enable the Django translation machinery you need to
9+
activate it with a language. **Note**: Using `translation.override`
10+
resets to the previous language automatically when it is exited. If you
11+
use `translation.activate` remember to reset to the previous language.
1112

1213
>>> from django.utils import translation
1314

14-
>>> prev_language = translation.get_language()
15-
>>> translation.activate(language)
16-
>>> try:
15+
>>> with translation.override(language):
1716
... render_template()
18-
... finally:
19-
translation.activate(prev_language)
2017

2118
The common pattern here would be for the task to take a ``language``
2219
argument:
@@ -30,12 +27,10 @@ argument:
3027

3128
@task()
3229
def generate_report(template="report.html", language=None):
33-
prev_language = translation.get_language()
34-
language and translation.activate(language)
35-
try:
30+
if language is None:
31+
language = translation.get_language()
32+
with translation.override(language)
3633
report = render_to_string(template)
37-
finally:
38-
translation.activate(prev_language)
3934
save_report_somewhere(report)
4035

4136
The celery test-suite is failing

0 commit comments

Comments
 (0)