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),
57 make_option('-k', '--keep-running', help='keep running even when missing an input file', dest='keep_running', default=False, action='store_true'),
59 help = 'Export models from app to po files'
62 def get_models(self, app):
64 for mdname in dir(app.models):
65 if mdname[0] == '_': continue
66 md = getattr(app.models, mdname)
68 opts = translator.get_options_for_model(md)
74 def handle(self, appname, **options):
75 if not options['poname']: options['poname'] = appname
76 app = __import__(appname)
81 for md, opts in self.get_models(app):
82 if not md.__name__ in objects:
83 objects[md.__name__] = {}
86 languages = get_languages(options['lang'])
88 for lng in zip(*languages)[0]:
89 pofile = os.path.join(options['directory'], lng, options['poname'] + '.po')
90 if not os.path.exists(pofile):
91 if options['keep_running']:
94 raise OSError('%s po file: %s not found' % (appname, pofile))
95 po = polib.pofile(pofile)
97 loc, pk = entry.occurrences[0]
98 _appname, modelname, fieldname = loc.split('/')
100 obj = objects[modelname][pk]
102 obj = modmod['model'].objects.get(pk=pk)
103 objects[modelname][pk] = obj
104 setattr(obj, fieldname, entry.msgstr)
106 for mod, objcs in objects.items():
107 for o in objcs.values():
112 for md, opts in self.get_models(app):
113 for obj in md.objects.all().order_by('pk'):
114 for fld in opts.fields:
115 for locfld in opts.localized_fieldnames[fld]:
116 cur_lang = lang(locfld)
118 po = pofiles[cur_lang]
120 po = make_po(cur_lang)
121 pofiles[cur_lang] = po
123 k = getattr(obj, '%s_%s' % (fld, settings.LANGUAGE_CODE))
125 v = getattr(obj, locfld)
127 entry = polib.POEntry(
130 occurrences=[('%s/%s/%s' % (appname, md.__name__, locfld), obj.id)])
133 directory = options['directory']
134 for lng, po in pofiles.items():
135 try: os.makedirs(os.path.join(directory, lng))
138 po.save(os.path.join(directory, lng, '%s.po' % options['poname']))