Skip to content

Instantly share code, notes, and snippets.

@Osmose
Created August 31, 2011 07:20
Show Gist options
  • Save Osmose/1182989 to your computer and use it in GitHub Desktop.
Save Osmose/1182989 to your computer and use it in GitHub Desktop.
import os
from optparse import make_option
from django.conf import settings
from django.core.management.base import BaseCommand, CommandError
from django.db.models.loading import get_model
from babel.messages.pofile import read_po, write_po
from tower.management.commands.extract import TEXT_DOMAIN, tweak_message
class Command(BaseCommand):
"""
Pulls strings from the database and appends them to an existing pot file.
The models and attributes to pull are defined by DB_LOCALIZE:
DB_LOCALIZE = {
'some_app': {
SomeModel': ['attr_name', 'another_attr'],
},
'another_app': {
AnotherModel': ['more_attrs'],
},
}
Database columns are expected to be CharFields or TextFields.
"""
help = ('Pulls strings from the database and appends them to an existing '
'.pot file.')
option_list = BaseCommand.option_list + (
make_option('--output-dir', '-o',
default=os.path.join(settings.ROOT, 'locale', 'templates',
'LC_MESSAGES'),
dest='outputdir',
help='The directory where extracted files are located.'
'(Default: %default)'),
)
def handle(self, *args, **options):
try:
apps = settings.DB_LOCALIZE
except NameError:
raise CommandError('DB_LOCALIZE setting is not defined!')
strings = []
# Oh god this is terrible
for app, models in apps.items():
for model, attrs in models.items():
model_class = get_model(app, model)
for item in model_class.objects.all():
for attr in attrs:
strings.append(getattr(item, attr))
po_dir = os.path.abspath(options.get('outputdir'))
po_filename = os.path.join(po_dir, '%s.pot' % TEXT_DOMAIN)
with open(po_filename, 'r') as f:
catalog = read_po(f)
for msg in strings:
catalog.add(tweak_message(msg))
with open(po_filename, 'w+') as f:
write_po(f, catalog)
@jbalogh
Copy link

jbalogh commented Aug 31, 2011

51: Please don't pull all the objects from the database, use .values_list().

I suspect this doesn't scale, but you probably have smaller usecases than I'm imagining.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment