5 from optparse import make_option
6 from django.conf import settings
7 from django.core.management.base import BaseCommand
8 from django.core.management.color import color_style
11 import modeltranslation.models
12 from modeltranslation.translator import translator, NotRegistered
15 def metadata(language=''):
16 "get metadata for PO, given language code"
17 t = time.strftime('%Y-%m-%d %H:%M%z')
20 'Project-Id-Version': '1.0',
21 'Report-Msgid-Bugs-To': 'marcin.koziej@nowoczesnapolska.org.pl',
22 'POT-Creation-Date': '%s' % t,
23 'PO-Revision-Date': '%s' % t,
24 'Last-Translator': 'you <you@example.com>',
25 'Language-Team': '%s' % dict(settings.LANGUAGES).get(language, language),
26 'MIME-Version': '1.0',
27 'Content-Type': 'text/plain; charset=utf-8',
28 'Content-Transfer-Encoding': '8bit',
33 "Get the language code from localized field name"
34 return field_name.split('_')[-1]
37 def make_po(language=''):
38 "Create new POFile object for language code"
40 po.metadata = metadata(language)
44 def get_languages(langs):
45 if not langs: return settings.LANGUAGES
46 langs = langs.split(',')
47 lm = dict(settings.LANGUAGES)
48 return map(lambda l: (l, lm.get(l, l)), langs)
51 class Command(BaseCommand):
52 option_list = BaseCommand.option_list + (
53 make_option('-d', '--directory', help='Specify which directory should hold generated PO files', dest='directory'),
54 make_option('-l', '--load', help='load locales back to source', action='store_true', dest='load', default=False),
55 make_option('-L', '--language', help='locales to load', dest='lang', default=None),
56 make_option('-n', '--poname', help='name of the po file [no extension]', dest='poname', default=None),
58 help = 'Export models from app to po files'
61 def get_models(self, app):
63 for mdname in dir(app.models):
64 if mdname[0] == '_': continue
65 md = getattr(app.models, mdname)
67 opts = translator.get_options_for_model(md)
73 def handle(self, appname, **options):
74 if not options['poname']: options['poname'] = appname
75 app = __import__(appname)
80 for md, opts in self.get_models(app):
81 if not md.__name__ in objects:
82 objects[md.__name__] = {}
85 languages = get_languages(options['lang'])
87 for lng in zip(*languages)[0]:
88 pofile = os.path.join(options['directory'], lng, options['poname'] + '.po')
89 if not os.path.exists(pofile): raise OSError('%s po file: %s not found' % (appname, pofile))
90 po = polib.pofile(pofile)
92 loc, pk = entry.occurrences[0]
93 _appname, modelname, fieldname = loc.split('/')
95 obj = objects[modelname][pk]
97 obj = modmod['model'].objects.get(pk=pk)
98 objects[modelname][pk] = obj
99 setattr(obj, fieldname, entry.msgstr)
101 for mod, objcs in objects.items():
102 for o in objcs.values():
107 for md, opts in self.get_models(app):
108 for obj in md.objects.all().order_by('pk'):
109 for fld in opts.fields:
110 for locfld in opts.localized_fieldnames[fld]:
111 cur_lang = lang(locfld)
113 po = pofiles[cur_lang]
115 po = make_po(cur_lang)
116 pofiles[cur_lang] = po
118 k = getattr(obj, '%s_%s' % (fld, settings.LANGUAGE_CODE))
120 v = getattr(obj, locfld)
122 entry = polib.POEntry(
125 occurrences=[('%s/%s/%s' % (appname, md.__name__, locfld), obj.id)])
128 directory = options['directory']
129 for lng, po in pofiles.items():
130 try: os.makedirs(os.path.join(directory, lng))
133 po.save(os.path.join(directory, lng, '%s.po' % options['poname']))