Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP

Loading…

internationalization of manage.py output #86

Closed
wants to merge 1 commit into from

2 participants

@saippuakauppias

No description provided.

@timgraham
Owner

If you're still interested in merging this please open a Trac ticket and a pull request for https://github.com/django/django/.

@timgraham timgraham closed this
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Commits on Nov 27, 2011
  1. @saippuakauppias

    add i18n

    saippuakauppias authored
This page is out of date. Refresh to see the latest.
Showing with 351 additions and 309 deletions.
  1. +10 −9 django/core/management/__init__.py
  2. +17 −16 django/core/management/base.py
  3. +2 −1  django/core/management/commands/cleanup.py
  4. +6 −5 django/core/management/commands/compilemessages.py
  5. +4 −3 django/core/management/commands/createcachetable.py
  6. +6 −5 django/core/management/commands/dbshell.py
  7. +3 −2 django/core/management/commands/diffsettings.py
  8. +18 −17 django/core/management/commands/dumpdata.py
  9. +10 −9 django/core/management/commands/flush.py
  10. +20 −19 django/core/management/commands/inspectdb.py
  11. +34 −28 django/core/management/commands/loaddata.py
  12. +30 −29 django/core/management/commands/makemessages.py
  13. +13 −12 django/core/management/commands/reset.py
  14. +2 −1  django/core/management/commands/runfcgi.py
  15. +18 −17 django/core/management/commands/runserver.py
  16. +3 −2 django/core/management/commands/shell.py
  17. +4 −3 django/core/management/commands/sql.py
  18. +4 −3 django/core/management/commands/sqlall.py
  19. +4 −3 django/core/management/commands/sqlclear.py
  20. +4 −3 django/core/management/commands/sqlcustom.py
  21. +4 −3 django/core/management/commands/sqlflush.py
  22. +4 −3 django/core/management/commands/sqlindexes.py
  23. +3 −2 django/core/management/commands/sqlinitialdata.py
  24. +4 −3 django/core/management/commands/sqlreset.py
  25. +4 −3 django/core/management/commands/sqlsequencereset.py
  26. +3 −2 django/core/management/commands/startapp.py
  27. +3 −2 django/core/management/commands/startproject.py
  28. +17 −16 django/core/management/commands/syncdb.py
  29. +6 −5 django/core/management/commands/test.py
  30. +6 −5 django/core/management/commands/testserver.py
  31. +2 −1  django/core/management/commands/validate.py
  32. +5 −4 django/core/management/sql.py
  33. +78 −73 django/core/management/validation.py
View
19 django/core/management/__init__.py
@@ -7,6 +7,7 @@
import django
from django.core.management.base import BaseCommand, CommandError, handle_default_options
from django.utils.importlib import import_module
+from django.utils.translation import ugettext as _
# For backwards compatibility: get_version() used to be in this module.
get_version = django.get_version
@@ -134,7 +135,7 @@ def call_command(name, *args, **options):
else:
klass = load_command_class(app_name, name)
except KeyError:
- raise CommandError("Unknown command: %r" % name)
+ raise CommandError(_("Unknown command: %r") % name)
# Grab out a list of defaults from the options. optparse does this for us
# when the script runs from the command line, but since call_command can
@@ -216,8 +217,8 @@ def main_help_text(self):
"""
Returns the script's main help text, as a string.
"""
- usage = ['',"Type '%s help <subcommand>' for help on a specific subcommand." % self.prog_name,'']
- usage.append('Available subcommands:')
+ usage = ['',_("Type '%s help <subcommand>' for help on a specific subcommand.") % self.prog_name,'']
+ usage.append(_('Available subcommands:'))
commands = get_commands().keys()
commands.sort()
for cmd in commands:
@@ -233,8 +234,8 @@ def fetch_command(self, subcommand):
try:
app_name = get_commands()[subcommand]
except KeyError:
- sys.stderr.write("Unknown command: %r\nType '%s help' for usage.\n" % \
- (subcommand, self.prog_name))
+ sys.stderr.write(_("Unknown command: %(subcommand)r\nType '%(prog_name)s help' for usage.\n") % \
+ {'subcommand': subcommand, 'prog_name': self.prog_name})
sys.exit(1)
if isinstance(app_name, BaseCommand):
# If the command is already loaded, use it directly.
@@ -371,10 +372,10 @@ def setup_environ(settings_mod, original_settings_path=None):
trying to work out the original path from the module can be problematic.
"""
warnings.warn(
- "The 'setup_environ' function is deprecated, "
+ _("The 'setup_environ' function is deprecated, "
"you likely need to update your 'manage.py'; "
"please see the Django 1.4 release notes "
- "(https://docs.djangoproject.com/en/dev/releases/1.4/).",
+ "(https://docs.djangoproject.com/en/dev/releases/1.4/)."),
PendingDeprecationWarning)
# Add this project to sys.path so that it's importable in the conventional
@@ -427,10 +428,10 @@ def execute_manager(settings_mod, argv=None):
project-specific django-admin.py utility.
"""
warnings.warn(
- "The 'execute_manager' function is deprecated, "
+ _("The 'execute_manager' function is deprecated, "
"you likely need to update your 'manage.py'; "
"please see the Django 1.4 release notes "
- "(https://docs.djangoproject.com/en/dev/releases/1.4/).",
+ "(https://docs.djangoproject.com/en/dev/releases/1.4/)."),
PendingDeprecationWarning)
setup_environ(settings_mod)
View
33 django/core/management/base.py
@@ -12,6 +12,7 @@
from django.core.exceptions import ImproperlyConfigured
from django.core.management.color import color_style
from django.utils.encoding import smart_str
+from django.utils.translation import ugettext as _
class CommandError(Exception):
"""
@@ -119,13 +120,13 @@ class BaseCommand(object):
option_list = (
make_option('-v', '--verbosity', action='store', dest='verbosity', default='1',
type='choice', choices=['0', '1', '2', '3'],
- help='Verbosity level; 0=minimal output, 1=normal output, 2=verbose output 3=very verbose output'),
+ help=_('Verbosity level; 0=minimal output, 1=normal output, 2=verbose output 3=very verbose output')),
make_option('--settings',
- help='The Python path to a settings module, e.g. "myproject.settings.main". If this isn\'t provided, the DJANGO_SETTINGS_MODULE environment variable will be used.'),
+ help=_('The Python path to a settings module, e.g. "myproject.settings.main". If this isn\'t provided, the DJANGO_SETTINGS_MODULE environment variable will be used.')),
make_option('--pythonpath',
- help='A directory to add to the Python path, e.g. "/home/djangoprojects/myproject".'),
+ help=_('A directory to add to the Python path, e.g. "/home/djangoprojects/myproject".')),
make_option('--traceback', action='store_true',
- help='Print traceback on exception'),
+ help=_('Print traceback on exception')),
)
help = ''
args = ''
@@ -212,7 +213,7 @@ def execute(self, *args, **options):
except ImportError, e:
# If settings should be available, but aren't,
# raise the error and quit.
- sys.stderr.write(smart_str(self.style.ERROR('Error: %s\n' % e)))
+ sys.stderr.write(smart_str(self.style.ERROR(_('Error: %s\n') % e)))
sys.exit(1)
try:
self.stdout = options.get('stdout', sys.stdout)
@@ -232,7 +233,7 @@ def execute(self, *args, **options):
if self.output_transaction:
self.stdout.write('\n' + self.style.SQL_KEYWORD("COMMIT;") + '\n')
except CommandError, e:
- self.stderr.write(smart_str(self.style.ERROR('Error: %s\n' % e)))
+ self.stderr.write(smart_str(self.style.ERROR(_('Error: %s\n') % e)))
sys.exit(1)
if saved_lang is not None:
translation.activate(saved_lang)
@@ -254,9 +255,9 @@ def validate(self, app=None, display_num_errors=False):
if num_errors:
s.seek(0)
error_text = s.read()
- raise CommandError("One or more models did not validate:\n%s" % error_text)
+ raise CommandError(_("One or more models did not validate:\n%s") % error_text)
if display_num_errors:
- self.stdout.write("%s error%s found\n" % (num_errors, num_errors != 1 and 's' or ''))
+ self.stdout.write(_("%(num_errors)s error%(num_errors_plural)s found\n") % {'num_errors': num_errors, 'num_errors_plural': num_errors != 1 and _('s') or ''})
def handle(self, *args, **options):
"""
@@ -280,11 +281,11 @@ class AppCommand(BaseCommand):
def handle(self, *app_labels, **options):
from django.db import models
if not app_labels:
- raise CommandError('Enter at least one appname.')
+ raise CommandError(_('Enter at least one appname.'))
try:
app_list = [models.get_app(app_label) for app_label in app_labels]
except (ImproperlyConfigured, ImportError), e:
- raise CommandError("%s. Are you sure your INSTALLED_APPS setting is correct?" % e)
+ raise CommandError(_("%s. Are you sure your INSTALLED_APPS setting is correct?") % e)
output = []
for app in app_list:
app_output = self.handle_app(app, **options)
@@ -319,7 +320,7 @@ class LabelCommand(BaseCommand):
def handle(self, *labels, **options):
if not labels:
- raise CommandError('Enter at least one %s.' % self.label)
+ raise CommandError(_('Enter at least one %s.') % self.label)
output = []
for label in labels:
@@ -351,7 +352,7 @@ class NoArgsCommand(BaseCommand):
def handle(self, *args, **options):
if args:
- raise CommandError("Command doesn't accept any arguments")
+ raise CommandError(_("Command doesn't accept any arguments"))
return self.handle_noargs(**options)
def handle_noargs(self, **options):
@@ -377,10 +378,10 @@ def copy_helper(style, app_or_project, name, directory):
if not re.search(r'^[_a-zA-Z]\w*$', name): # If it's not a valid directory name.
# Provide a smart error message, depending on the error.
if not re.search(r'^[_a-zA-Z]', name):
- message = 'make sure the name begins with a letter or underscore'
+ message = _('make sure the name begins with a letter or underscore')
else:
- message = 'use only numbers, letters and underscores'
- raise CommandError("%r is not a valid %s name. Please %s." % (name, app_or_project, message))
+ message = _('use only numbers, letters and underscores')
+ raise CommandError(_("%(name)r is not a valid %(app_or_project)s name. Please %(message)s.") % {'name': name, 'app_or_project': app_or_project, 'message': message})
top_dir = os.path.join(directory, name)
try:
os.mkdir(top_dir)
@@ -415,7 +416,7 @@ def copy_helper(style, app_or_project, name, directory):
shutil.copymode(path_old, path_new)
_make_writeable(path_new)
except OSError:
- sys.stderr.write(style.NOTICE("Notice: Couldn't set permission bits on %s. You're probably using an uncommon filesystem setup. No problem.\n" % path_new))
+ sys.stderr.write(style.NOTICE(_("Notice: Couldn't set permission bits on %s. You're probably using an uncommon filesystem setup. No problem.\n") % path_new))
def _make_writeable(filename):
"""
View
3  django/core/management/commands/cleanup.py
@@ -1,8 +1,9 @@
from django.core.management.base import NoArgsCommand
from django.utils import timezone
+from django.utils.translation import ugettext as _
class Command(NoArgsCommand):
- help = "Can be run as a cronjob or directly to clean out old data from the database (only expired sessions at the moment)."
+ help = _("Can be run as a cronjob or directly to clean out old data from the database (only expired sessions at the moment).")
def handle_noargs(self, **options):
from django.db import transaction
View
11 django/core/management/commands/compilemessages.py
@@ -3,6 +3,7 @@
import sys
from optparse import make_option
from django.core.management.base import BaseCommand, CommandError
+from django.utils.translation import ugettext as _
def has_bom(fn):
f = open(fn, 'r')
@@ -21,7 +22,7 @@ def compile_messages(stderr, locale=None):
basedirs = set(map(os.path.abspath, filter(os.path.isdir, basedirs)))
if not basedirs:
- raise CommandError("This script should be run from the Django SVN tree or your project or app tree, or with the settings module specified.")
+ raise CommandError(_("This script should be run from the Django SVN tree or your project or app tree, or with the settings module specified."))
for basedir in basedirs:
if locale:
@@ -29,10 +30,10 @@ def compile_messages(stderr, locale=None):
for dirpath, dirnames, filenames in os.walk(basedir):
for f in filenames:
if f.endswith('.po'):
- stderr.write('processing file %s in %s\n' % (f, dirpath))
+ stderr.write(_('processing file %(file)s in %(dirpath)s\n') % {'file': f, 'dirpath': dirpath})
fn = os.path.join(dirpath, f)
if has_bom(fn):
- raise CommandError("The %s file has a BOM (Byte Order Mark). Django only supports .po files encoded in UTF-8 and without any BOM." % fn)
+ raise CommandError(_("The %s file has a BOM (Byte Order Mark). Django only supports .po files encoded in UTF-8 and without any BOM.") % fn)
pf = os.path.splitext(fn)[0]
# Store the names of the .mo and .po files in an environment
# variable, rather than doing a string replacement into the
@@ -51,9 +52,9 @@ def compile_messages(stderr, locale=None):
class Command(BaseCommand):
option_list = BaseCommand.option_list + (
make_option('--locale', '-l', dest='locale',
- help='The locale to process. Default is to process all.'),
+ help=_('The locale to process. Default is to process all.')),
)
- help = 'Compiles .po files to .mo files for use with builtin gettext support.'
+ help = _('Compiles .po files to .mo files for use with builtin gettext support.')
requires_model_validation = False
can_import_settings = False
View
7 django/core/management/commands/createcachetable.py
@@ -3,17 +3,18 @@
from django.core.cache.backends.db import BaseDatabaseCache
from django.core.management.base import LabelCommand
from django.db import connections, router, transaction, models, DEFAULT_DB_ALIAS
+from django.utils.translation import ugettext as _
class Command(LabelCommand):
- help = "Creates the table needed to use the SQL cache backend."
+ help = _("Creates the table needed to use the SQL cache backend.")
args = "<tablename>"
label = 'tablename'
option_list = LabelCommand.option_list + (
make_option('--database', action='store', dest='database',
- default=DEFAULT_DB_ALIAS, help='Nominates a database onto '
+ default=DEFAULT_DB_ALIAS, help=_('Nominates a database onto '
'which the cache table will be installed. '
- 'Defaults to the "default" database.'),
+ 'Defaults to the "default" database.')),
)
requires_model_validation = False
View
11 django/core/management/commands/dbshell.py
@@ -1,16 +1,17 @@
from optparse import make_option
from django.core.management.base import BaseCommand, CommandError
-from django.db import connections, DEFAULT_DB_ALIAS
+from django.db import connections,
+from django.utils.translation import ugettext as _
class Command(BaseCommand):
- help = ("Runs the command-line client for specified database, or the "
+ help = _("Runs the command-line client for specified database, or the "
"default database if none is provided.")
option_list = BaseCommand.option_list + (
make_option('--database', action='store', dest='database',
- default=DEFAULT_DB_ALIAS, help='Nominates a database onto which to '
- 'open a shell. Defaults to the "default" database.'),
+ default=DEFAULT_DB_ALIAS, help=_('Nominates a database onto which to '
+ 'open a shell. Defaults to the "default" database.')),
)
requires_model_validation = False
@@ -24,5 +25,5 @@ def handle(self, **options):
# isn't installed. There's a possibility OSError would be raised
# for some other reason, in which case this error message would be
# inaccurate. Still, this message catches the common case.
- raise CommandError('You appear not to have the %r program installed or on your path.' % \
+ raise CommandError(_('You appear not to have the %r program installed or on your path.') % \
connection.client.executable_name)
View
5 django/core/management/commands/diffsettings.py
@@ -1,13 +1,14 @@
from django.core.management.base import NoArgsCommand
+from django.utils.translation import ugettext as _
def module_to_dict(module, omittable=lambda k: k.startswith('_')):
"Converts a module namespace to a Python dictionary. Used by get_settings_diff."
return dict([(k, repr(v)) for k, v in module.__dict__.items() if not omittable(k)])
class Command(NoArgsCommand):
- help = """Displays differences between the current settings.py and Django's
+ help = _("""Displays differences between the current settings.py and Django's
default settings. Settings that don't appear in the defaults are
- followed by "###"."""
+ followed by "###".""")
requires_model_validation = False
View
35 django/core/management/commands/dumpdata.py
@@ -3,26 +3,27 @@
from django.core import serializers
from django.db import router, DEFAULT_DB_ALIAS
from django.utils.datastructures import SortedDict
+from django.utils.translation import ugettext as _
from optparse import make_option
class Command(BaseCommand):
option_list = BaseCommand.option_list + (
make_option('--format', default='json', dest='format',
- help='Specifies the output serialization format for fixtures.'),
+ help=_('Specifies the output serialization format for fixtures.')),
make_option('--indent', default=None, dest='indent', type='int',
- help='Specifies the indent level to use when pretty-printing output'),
+ help=_('Specifies the indent level to use when pretty-printing output')),
make_option('--database', action='store', dest='database',
- default=DEFAULT_DB_ALIAS, help='Nominates a specific database to dump '
- 'fixtures from. Defaults to the "default" database.'),
+ default=DEFAULT_DB_ALIAS, help=_('Nominates a specific database to dump '
+ 'fixtures from. Defaults to the "default" database.')),
make_option('-e', '--exclude', dest='exclude',action='append', default=[],
- help='An appname or appname.ModelName to exclude (use multiple --exclude to exclude multiple apps/models).'),
+ help=_('An appname or appname.ModelName to exclude (use multiple --exclude to exclude multiple apps/models).')),
make_option('-n', '--natural', action='store_true', dest='use_natural_keys', default=False,
- help='Use natural keys if they are available.'),
+ help=_('Use natural keys if they are available.')),
make_option('-a', '--all', action='store_true', dest='use_base_manager', default=False,
- help="Use Django's base manager to dump all models stored in the database, including those that would otherwise be filtered or modified by a custom manager."),
+ help=_("Use Django's base manager to dump all models stored in the database, including those that would otherwise be filtered or modified by a custom manager.")),
)
- help = ("Output the contents of the database as a fixture of the given "
+ help = _("Output the contents of the database as a fixture of the given "
"format (using each model's default manager unless --all is "
"specified).")
args = '[appname appname.ModelName ...]'
@@ -45,14 +46,14 @@ def handle(self, *app_labels, **options):
app_label, model_name = exclude.split('.', 1)
model_obj = get_model(app_label, model_name)
if not model_obj:
- raise CommandError('Unknown model in excludes: %s' % exclude)
+ raise CommandError(_('Unknown model in excludes: %s') % exclude)
excluded_models.add(model_obj)
else:
try:
app_obj = get_app(exclude)
excluded_apps.add(app_obj)
except ImproperlyConfigured:
- raise CommandError('Unknown app in excludes: %s' % exclude)
+ raise CommandError(_('Unknown app in excludes: %s') % exclude)
if len(app_labels) == 0:
app_list = SortedDict((app, None) for app in get_apps() if app not in excluded_apps)
@@ -64,12 +65,12 @@ def handle(self, *app_labels, **options):
try:
app = get_app(app_label)
except ImproperlyConfigured:
- raise CommandError("Unknown application: %s" % app_label)
+ raise CommandError(_("Unknown application: %s") % app_label)
if app in excluded_apps:
continue
model = get_model(app_label, model_label)
if model is None:
- raise CommandError("Unknown model: %s.%s" % (app_label, model_label))
+ raise CommandError(_("Unknown model: %(app_label)s.%(model_label)s") % {'app_label': app_label, 'model_label': model_label})
if app in app_list.keys():
if app_list[app] and model not in app_list[app]:
@@ -82,7 +83,7 @@ def handle(self, *app_labels, **options):
try:
app = get_app(app_label)
except ImproperlyConfigured:
- raise CommandError("Unknown application: %s" % app_label)
+ raise CommandError(_("Unknown application: %s") % app_label)
if app in excluded_apps:
continue
app_list[app] = None
@@ -90,12 +91,12 @@ def handle(self, *app_labels, **options):
# Check that the serialization format exists; this is a shortcut to
# avoid collating all the objects and _then_ failing.
if format not in serializers.get_public_serializer_formats():
- raise CommandError("Unknown serialization format: %s" % format)
+ raise CommandError(_("Unknown serialization format: %s") % format)
try:
serializers.get_serializer(format)
except KeyError:
- raise CommandError("Unknown serialization format: %s" % format)
+ raise CommandError(_("Unknown serialization format: %s") % format)
# Now collate the objects to be serialized.
objects = []
@@ -114,7 +115,7 @@ def handle(self, *app_labels, **options):
except Exception, e:
if show_traceback:
raise
- raise CommandError("Unable to serialize database: %s" % e)
+ raise CommandError(_("Unable to serialize database: %s") % e)
def sort_dependencies(app_list):
"""Sort a list of app,modellist pairs into a single list of models.
@@ -183,7 +184,7 @@ def sort_dependencies(app_list):
else:
skipped.append((model, deps))
if not changed:
- raise CommandError("Can't resolve dependencies for %s in serialized app list." %
+ raise CommandError(_("Can't resolve dependencies for %s in serialized app list.") %
', '.join('%s.%s' % (model._meta.app_label, model._meta.object_name)
for model, deps in sorted(skipped, key=lambda obj: obj[0].__name__))
)
View
19 django/core/management/commands/flush.py
@@ -7,17 +7,18 @@
from django.core.management.color import no_style
from django.core.management.sql import sql_flush, emit_post_sync_signal
from django.utils.importlib import import_module
+from django.utils.translation import ugettext as _
class Command(NoArgsCommand):
option_list = NoArgsCommand.option_list + (
make_option('--noinput', action='store_false', dest='interactive', default=True,
- help='Tells Django to NOT prompt the user for input of any kind.'),
+ help=_('Tells Django to NOT prompt the user for input of any kind.')),
make_option('--database', action='store', dest='database',
- default=DEFAULT_DB_ALIAS, help='Nominates a database to flush. '
- 'Defaults to the "default" database.'),
+ default=DEFAULT_DB_ALIAS, help=_('Nominates a database to flush. '
+ 'Defaults to the "default" database.')),
)
- help = ('Returns the database to the state it was in immediately after '
+ help = _('Returns the database to the state it was in immediately after '
'syncdb was executed. This means that all data will be removed '
'from the database, any post-synchronization handlers will be '
're-executed, and the initial_data fixture will be re-installed.')
@@ -41,12 +42,12 @@ def handle_noargs(self, **options):
sql_list = sql_flush(self.style, connection, only_django=True)
if interactive:
- confirm = raw_input("""You have requested a flush of the database.
+ confirm = raw_input(_("""You have requested a flush of the database.
This will IRREVERSIBLY DESTROY all data currently in the %r database,
and return each table to the state it was in after syncdb.
Are you sure you want to do this?
- Type 'yes' to continue, or 'no' to cancel: """ % connection.settings_dict['NAME'])
+ Type 'yes' to continue, or 'no' to cancel: """) % connection.settings_dict['NAME'])
else:
confirm = 'yes'
@@ -57,12 +58,12 @@ def handle_noargs(self, **options):
cursor.execute(sql)
except Exception, e:
transaction.rollback_unless_managed(using=db)
- raise CommandError("""Database %s couldn't be flushed. Possible reasons:
+ raise CommandError(_("""Database %(connection_name)s couldn't be flushed. Possible reasons:
* The database isn't running or isn't configured correctly.
* At least one of the expected database tables doesn't exist.
* The SQL was invalid.
Hint: Look at the output of 'django-admin.py sqlflush'. That's the SQL this command wasn't able to run.
-The full error: %s""" % (connection.settings_dict['NAME'], e))
+The full error: %(error)s""") % {'connection_name': connection.settings_dict['NAME'], 'error': e})
transaction.commit_unless_managed(using=db)
# Emit the post sync signal. This allows individual
@@ -82,4 +83,4 @@ def handle_noargs(self, **options):
call_command('loaddata', 'initial_data', **kwargs)
else:
- print "Flush cancelled."
+ print _("Flush cancelled.")
View
39 django/core/management/commands/inspectdb.py
@@ -3,14 +3,15 @@
from django.core.management.base import NoArgsCommand, CommandError
from django.db import connections, DEFAULT_DB_ALIAS
+from django.utils.translation import ugettext as _
class Command(NoArgsCommand):
- help = "Introspects the database tables in the given database and outputs a Django model module."
+ help = _("Introspects the database tables in the given database and outputs a Django model module.")
option_list = NoArgsCommand.option_list + (
make_option('--database', action='store', dest='database',
- default=DEFAULT_DB_ALIAS, help='Nominates a database to '
- 'introspect. Defaults to using the "default" database.'),
+ default=DEFAULT_DB_ALIAS, help=_('Nominates a database to '
+ 'introspect. Defaults to using the "default" database.')),
)
requires_model_validation = False
@@ -22,7 +23,7 @@ def handle_noargs(self, **options):
for line in self.handle_inspection(options):
self.stdout.write("%s\n" % line)
except NotImplementedError:
- raise CommandError("Database inspection isn't supported for the currently selected database backend.")
+ raise CommandError(_("Database inspection isn't supported for the currently selected database backend."))
def handle_inspection(self, options):
connection = connections[options.get('database')]
@@ -30,16 +31,16 @@ def handle_inspection(self, options):
table2model = lambda table_name: table_name.title().replace('_', '').replace(' ', '').replace('-', '')
cursor = connection.cursor()
- yield "# This is an auto-generated Django model module."
- yield "# You'll have to do the following manually to clean this up:"
- yield "# * Rearrange models' order"
- yield "# * Make sure each model has one field with primary_key=True"
- yield "# Feel free to rename the models, but don't rename db_table values or field names."
+ yield _("# This is an auto-generated Django model module.")
+ yield _("# You'll have to do the following manually to clean this up:")
+ yield _("# * Rearrange models' order")
+ yield _("# * Make sure each model has one field with primary_key=True")
+ yield _("# Feel free to rename the models, but don't rename db_table values or field names.")
yield "#"
- yield "# Also note: You'll have to insert the output of 'django-admin.py sqlcustom [appname]'"
- yield "# into your database."
+ yield _("# Also note: You'll have to insert the output of 'django-admin.py sqlcustom [appname]'")
+ yield _("# into your database.")
yield ''
- yield 'from %s import models' % self.db_module
+ yield _('from %s import models') % self.db_module
yield ''
for table_name in connection.introspection.get_table_list(cursor):
yield 'class %s(models.Model):' % table2model(table_name)
@@ -65,14 +66,14 @@ def handle_inspection(self, options):
# Modify the field name to make it Python-compatible.
if ' ' in att_name:
att_name = att_name.replace(' ', '_')
- comment_notes.append('Field renamed to remove spaces.')
+ comment_notes.append(_('Field renamed to remove spaces.'))
if '-' in att_name:
att_name = att_name.replace('-', '_')
- comment_notes.append('Field renamed to remove dashes.')
+ comment_notes.append(_('Field renamed to remove dashes.'))
if column_name != att_name:
- comment_notes.append('Field name made lowercase.')
+ comment_notes.append(_('Field name made lowercase.'))
if i in relations:
rel_to = relations[i][1] == table_name and "'self'" or table2model(relations[i][1])
@@ -99,13 +100,13 @@ def handle_inspection(self, options):
if keyword.iskeyword(att_name):
att_name += '_field'
- comment_notes.append('Field renamed because it was a Python reserved word.')
+ comment_notes.append(_('Field renamed because it was a Python reserved word.'))
if att_name.isdigit():
att_name = 'number_%d' % int(att_name)
extra_params['db_column'] = unicode(column_name)
- comment_notes.append("Field renamed because it wasn't a "
- "valid Python identifier.")
+ comment_notes.append(_("Field renamed because it wasn't a "
+ "valid Python identifier."))
# Don't output 'id = meta.AutoField(primary_key=True)', because
# that's assumed if it doesn't exist.
@@ -144,7 +145,7 @@ def get_field_type(self, connection, table_name, row):
field_type = connection.introspection.get_field_type(row[1], row)
except KeyError:
field_type = 'TextField'
- field_notes.append('This field type is a guess.')
+ field_notes.append(_('This field type is a guess.'))
# This is a hook for DATA_TYPES_REVERSE to return a tuple of
# (field_type, field_params_dict).
View
62 django/core/management/commands/loaddata.py
@@ -16,6 +16,7 @@
IntegrityError, DatabaseError)
from django.db.models import get_apps
from django.utils.itercompat import product
+from django.utils.translation import ugettext as _
try:
import bz2
@@ -24,13 +25,13 @@
has_bz2 = False
class Command(BaseCommand):
- help = 'Installs the named fixture(s) in the database.'
+ help = _('Installs the named fixture(s) in the database.')
args = "fixture [fixture ...]"
option_list = BaseCommand.option_list + (
make_option('--database', action='store', dest='database',
- default=DEFAULT_DB_ALIAS, help='Nominates a specific database to load '
- 'fixtures into. Defaults to the "default" database.'),
+ default=DEFAULT_DB_ALIAS, help=_('Nominates a specific database to load '
+ 'fixtures into. Defaults to the "default" database.')),
)
def handle(self, *fixture_labels, **options):
@@ -41,7 +42,7 @@ def handle(self, *fixture_labels, **options):
if not len(fixture_labels):
self.stderr.write(
- self.style.ERROR("No database fixture specified. Please provide the path of at least one fixture in the command line.\n")
+ self.style.ERROR(_("No database fixture specified. Please provide the path of at least one fixture in the command line.\n"))
)
return
@@ -62,7 +63,7 @@ def handle(self, *fixture_labels, **options):
fixture_object_count = 0
models = set()
- humanize = lambda dirname: "'%s'" % dirname if dirname else 'absolute path'
+ humanize = lambda dirname: "'%s'" % dirname if dirname else _('absolute path')
# Get a cursor (even though we don't need one yet). This has
# the side effect of initializing the test database (if
@@ -80,7 +81,7 @@ class SingleZipReader(zipfile.ZipFile):
def __init__(self, *args, **kwargs):
zipfile.ZipFile.__init__(self, *args, **kwargs)
if settings.DEBUG:
- assert len(self.namelist()) == 1, "Zip-compressed fixtures must contain only one file."
+ assert len(self.namelist()) == 1, _("Zip-compressed fixtures must contain only one file.")
def read(self):
return zipfile.ZipFile.read(self, self.namelist()[0])
@@ -124,11 +125,11 @@ def read(self):
if formats:
if verbosity >= 2:
- self.stdout.write("Loading '%s' fixtures...\n" % fixture_name)
+ self.stdout.write(_("Loading '%s' fixtures...\n") % fixture_name)
else:
self.stderr.write(
- self.style.ERROR("Problem installing fixture '%s': %s is not a known serialization format.\n" %
- (fixture_name, format)))
+ self.style.ERROR(_("Problem installing fixture '%(fixture_name)s': %(format)s is not a known serialization format.\n") %
+ {'fixture_name': fixture_name, 'format': format}))
if commit:
transaction.rollback(using=using)
transaction.leave_transaction_management(using=using)
@@ -141,7 +142,7 @@ def read(self):
for fixture_dir in fixture_dirs:
if verbosity >= 2:
- self.stdout.write("Checking %s for fixtures...\n" % humanize(fixture_dir))
+ self.stdout.write(_("Checking %s for fixtures...\n") % humanize(fixture_dir))
label_found = False
for combo in product([using, None], formats, compression_formats):
@@ -154,21 +155,21 @@ def read(self):
)
if verbosity >= 3:
- self.stdout.write("Trying %s for %s fixture '%s'...\n" % \
- (humanize(fixture_dir), file_name, fixture_name))
+ self.stdout.write(_("Trying %(fixture_dir)s for %(file_name)s fixture '%(fixture_name)s'...\n") % \
+ {'fixture_dir': humanize(fixture_dir), 'file_name': file_name, 'fixture_name': fixture_name})
full_path = os.path.join(fixture_dir, file_name)
open_method = compression_types[compression_format]
try:
fixture = open_method(full_path, 'r')
except IOError:
if verbosity >= 2:
- self.stdout.write("No %s fixture '%s' in %s.\n" % \
- (format, fixture_name, humanize(fixture_dir)))
+ self.stdout.write(_("No %(format)s fixture '%(fixture_name)s' in %(fixture_dir)s.\n") % \
+ {'format': format, 'fixture_name': fixture_name, 'fixture_dir': humanize(fixture_dir)})
else:
if label_found:
fixture.close()
- self.stderr.write(self.style.ERROR("Multiple fixtures named '%s' in %s. Aborting.\n" %
- (fixture_name, humanize(fixture_dir))))
+ self.stderr.write(self.style.ERROR(_("Multiple fixtures named '%(fixture_name)s' in %(fixture_dir)s. Aborting.\n") %
+ {'fixture_name': fixture_name, 'fixture_dir': humanize(fixture_dir)}))
if commit:
transaction.rollback(using=using)
transaction.leave_transaction_management(using=using)
@@ -178,8 +179,8 @@ def read(self):
objects_in_fixture = 0
loaded_objects_in_fixture = 0
if verbosity >= 2:
- self.stdout.write("Installing %s fixture '%s' from %s.\n" % \
- (format, fixture_name, humanize(fixture_dir)))
+ self.stdout.write(_("Installing %(format)s fixture '%(fixture_name)s' from %(fixture_dir)s.\n") % \
+ {'format': format, 'fixture_name': fixture_name, 'fixture_dir': humanize(fixture_dir)})
try:
objects = serializers.deserialize(format, fixture, using=using)
@@ -192,7 +193,7 @@ def read(self):
try:
obj.save(using=using)
except (DatabaseError, IntegrityError), e:
- msg = "Could not load %(app_label)s.%(object_name)s(pk=%(pk)s): %(error_msg)s" % {
+ msg = _("Could not load %(app_label)s.%(object_name)s(pk=%(pk)s): %(error_msg)s") % {
'app_label': obj.object._meta.app_label,
'object_name': obj.object._meta.object_name,
'pk': obj.object.pk,
@@ -220,9 +221,9 @@ def read(self):
traceback.print_exc()
else:
self.stderr.write(
- self.style.ERROR("Problem installing fixture '%s': %s\n" %
- (full_path, ''.join(traceback.format_exception(sys.exc_type,
- sys.exc_value, sys.exc_traceback)))))
+ self.style.ERROR(_("Problem installing fixture '%(full_path)s': %(traceback)s\n") %
+ {'full_path': full_path, 'traceback': ''.join(traceback.format_exception(sys.exc_type,
+ sys.exc_value, sys.exc_traceback))}))
return
fixture.close()
@@ -230,7 +231,7 @@ def read(self):
# error was encountered during fixture loading.
if objects_in_fixture == 0:
self.stderr.write(
- self.style.ERROR("No fixture data found for '%s'. (File format may be invalid.)\n" %
+ self.style.ERROR(_("No fixture data found for '%s'. (File format may be invalid.)\n") %
(fixture_name)))
if commit:
transaction.rollback(using=using)
@@ -243,7 +244,7 @@ def read(self):
sequence_sql = connection.ops.sequence_reset_sql(self.style, models)
if sequence_sql:
if verbosity >= 2:
- self.stdout.write("Resetting sequences\n")
+ self.stdout.write(_("Resetting sequences\n"))
for line in sequence_sql:
cursor.execute(line)
@@ -253,11 +254,16 @@ def read(self):
if verbosity >= 1:
if fixture_object_count == loaded_object_count:
- self.stdout.write("Installed %d object(s) from %d fixture(s)\n" % (
- loaded_object_count, fixture_count))
+ self.stdout.write(_("Installed %(loaded_object_count)d object(s) from %(fixture_count)d fixture(s)\n") % {
+ 'loaded_object_count': loaded_object_count,
+ 'fixture_count': fixture_count
+ })
else:
- self.stdout.write("Installed %d object(s) (of %d) from %d fixture(s)\n" % (
- loaded_object_count, fixture_object_count, fixture_count))
+ self.stdout.write(_("Installed %(loaded_object_count)d object(s) (of %(fixture_object_count)d) from %(fixture_count)d fixture(s)\n") % {
+ 'loaded_object_count': loaded_object_count,
+ 'fixture_object_count': fixture_object_count,
+ 'fixture_count': fixture_count
+ })
# Close the DB connection. This is required as a workaround for an
# edge case in MySQL: if the same connection is used to
View
59 django/core/management/commands/makemessages.py
@@ -10,6 +10,7 @@
from django.core.management.base import CommandError, NoArgsCommand
from django.utils.text import get_text_list
from django.utils.jslex import prepare_js_for_gettext
+from django.utils.translation import ugettext as _
plural_forms_re = re.compile(r'^(?P<value>"Plural-Forms.+?\\n")\s*$', re.MULTILINE | re.DOTALL)
@@ -76,7 +77,7 @@ def find_files(root, ignore_patterns, verbosity, symlinks=False):
norm_filepath = os.path.normpath(os.path.join(dirpath, f))
if is_ignored(norm_filepath, ignore_patterns):
if verbosity > 1:
- sys.stdout.write('ignoring file %s in %s\n' % (f, dirpath))
+ sys.stdout.write(_('ignoring file %(file)s in %(dirpath)s\n') % {'file': f, 'dirpath': dirpath})
else:
all_files.extend([(dirpath, f)])
all_files.sort()
@@ -100,7 +101,7 @@ def copy_plural_forms(msgs, locale, domain, verbosity):
m = plural_forms_re.search(open(django_po, 'rU').read())
if m:
if verbosity > 1:
- sys.stderr.write("copying plural forms: %s\n" % m.group('value'))
+ sys.stderr.write(_("copying plural forms: %s\n") % m.group('value'))
lines = []
seen = False
for line in msgs.split('\n'):
@@ -139,13 +140,13 @@ def make_messages(locale=None, domain='django', verbosity='1', all=False,
elif os.path.isdir('locale'):
localedir = os.path.abspath('locale')
else:
- raise CommandError("This script should be run from the Django SVN tree or your project or app tree. If you did indeed run it from the SVN checkout or your project or application, maybe you are just missing the conf/locale (in the django tree) or locale (for project and application) directory? It is not created automatically, you have to create it by hand if you want to enable i18n for your project or application.")
+ raise CommandError(_("This script should be run from the Django SVN tree or your project or app tree. If you did indeed run it from the SVN checkout or your project or application, maybe you are just missing the conf/locale (in the django tree) or locale (for project and application) directory? It is not created automatically, you have to create it by hand if you want to enable i18n for your project or application."))
if domain not in ('django', 'djangojs'):
- raise CommandError("currently makemessages only supports domains 'django' and 'djangojs'")
+ raise CommandError(_("currently makemessages only supports domains 'django' and 'djangojs'"))
if (locale is None and not all) or domain is None:
- message = "Type '%s help %s' for usage information." % (os.path.basename(sys.argv[0]), sys.argv[1])
+ message = _("Type '%(arg0)s help %(arg1)s' for usage information.") % {'arg0': os.path.basename(sys.argv[0]), 'arg1': sys.argv[1]}
raise CommandError(message)
# We require gettext version 0.15 or newer.
@@ -154,7 +155,7 @@ def make_messages(locale=None, domain='django', verbosity='1', all=False,
if match:
xversion = (int(match.group('major')), int(match.group('minor')))
if xversion < (0, 15):
- raise CommandError("Django internationalization requires GNU gettext 0.15 or newer. You are using version %s, please upgrade your gettext toolset." % match.group())
+ raise CommandError(_("Django internationalization requires GNU gettext 0.15 or newer. You are using version %s, please upgrade your gettext toolset.") % match.group())
languages = []
if locale is not None:
@@ -168,7 +169,7 @@ def make_messages(locale=None, domain='django', verbosity='1', all=False,
for locale in languages:
if verbosity > 0:
- print "processing language", locale
+ print _("processing language"), locale
basedir = os.path.join(localedir, locale, 'LC_MESSAGES')
if not os.path.isdir(basedir):
os.makedirs(basedir)
@@ -183,7 +184,7 @@ def make_messages(locale=None, domain='django', verbosity='1', all=False,
file_base, file_ext = os.path.splitext(file)
if domain == 'djangojs' and file_ext in extensions:
if verbosity > 1:
- sys.stdout.write('processing file %s in %s\n' % (file, dirpath))
+ sys.stdout.write(_('processing file %(file)s in %(dirpath)s\n') % {'file': file, 'dirpath': dirpath})
src = open(os.path.join(dirpath, file), "rU").read()
src = prepare_js_for_gettext(src)
thefile = '%s.c' % file
@@ -206,8 +207,8 @@ def make_messages(locale=None, domain='django', verbosity='1', all=False,
if os.path.exists(potfile):
os.unlink(potfile)
raise CommandError(
- "errors happened while running xgettext on %s\n%s" %
- (file, errors))
+ _("errors happened while running xgettext on %(file)s\n%(errors)s") %
+ {'file': file, 'errors': errors})
if msgs:
old = '#: ' + os.path.join(dirpath, thefile)[2:]
new = '#: ' + os.path.join(dirpath, file)[2:]
@@ -235,7 +236,7 @@ def make_messages(locale=None, domain='django', verbosity='1', all=False,
finally:
f.close()
if verbosity > 1:
- sys.stdout.write('processing file %s in %s\n' % (file, dirpath))
+ sys.stdout.write(_('processing file %(file)s in %(dirpath)s\n') % {'file': file, 'dirpath': dirpath})
cmd = (
'xgettext -d %s -L Python %s %s --keyword=gettext_noop '
'--keyword=gettext_lazy --keyword=ngettext_lazy:1,2 '
@@ -253,8 +254,8 @@ def make_messages(locale=None, domain='django', verbosity='1', all=False,
if os.path.exists(potfile):
os.unlink(potfile)
raise CommandError(
- "errors happened while running xgettext on %s\n%s" %
- (file, errors))
+ _("errors happened while running xgettext on %(file)s\n%(errors)s") %
+ {'file': file, 'errors': errors})
if msgs:
if thefile != file:
old = '#: ' + os.path.join(dirpath, thefile)[2:]
@@ -279,7 +280,7 @@ def make_messages(locale=None, domain='django', verbosity='1', all=False,
if errors:
os.unlink(potfile)
raise CommandError(
- "errors happened while running msguniq\n%s" % errors)
+ _("errors happened while running msguniq\n%s") % errors)
if os.path.exists(pofile):
f = open(potfile, 'w')
try:
@@ -291,7 +292,7 @@ def make_messages(locale=None, domain='django', verbosity='1', all=False,
if errors:
os.unlink(potfile)
raise CommandError(
- "errors happened while running msgmerge\n%s" % errors)
+ _("errors happened while running msgmerge\n%s") % errors)
elif not invoked_for_django:
msgs = copy_plural_forms(msgs, locale, domain, verbosity)
msgs = msgs.replace(
@@ -307,34 +308,34 @@ def make_messages(locale=None, domain='django', verbosity='1', all=False,
(wrap, location, pofile, pofile))
if errors:
raise CommandError(
- "errors happened while running msgattrib\n%s" % errors)
+ _("errors happened while running msgattrib\n%s") % errors)
class Command(NoArgsCommand):
option_list = NoArgsCommand.option_list + (
make_option('--locale', '-l', default=None, dest='locale',
- help='Creates or updates the message files for the given locale (e.g. pt_BR).'),
+ help=_('Creates or updates the message files for the given locale (e.g. pt_BR).')),
make_option('--domain', '-d', default='django', dest='domain',
- help='The domain of the message files (default: "django").'),
+ help=_('The domain of the message files (default: "django").')),
make_option('--all', '-a', action='store_true', dest='all',
- default=False, help='Updates the message files for all existing locales.'),
+ default=False, help=_('Updates the message files for all existing locales.')),
make_option('--extension', '-e', dest='extensions',
- help='The file extension(s) to examine (default: "html,txt", or "js" if the domain is "djangojs"). Separate multiple extensions with commas, or use -e multiple times.',
+ help=_('The file extension(s) to examine (default: "html,txt", or "js" if the domain is "djangojs"). Separate multiple extensions with commas, or use -e multiple times.'),
action='append'),
make_option('--symlinks', '-s', action='store_true', dest='symlinks',
- default=False, help='Follows symlinks to directories when examining source code and templates for translation strings.'),
+ default=False, help=_('Follows symlinks to directories when examining source code and templates for translation strings.')),
make_option('--ignore', '-i', action='append', dest='ignore_patterns',
- default=[], metavar='PATTERN', help='Ignore files or directories matching this glob-style pattern. Use multiple times to ignore more.'),
+ default=[], metavar='PATTERN', help=_('Ignore files or directories matching this glob-style pattern. Use multiple times to ignore more.')),
make_option('--no-default-ignore', action='store_false', dest='use_default_ignore_patterns',
- default=True, help="Don't ignore the common glob-style patterns 'CVS', '.*' and '*~'."),
+ default=True, help=_("Don't ignore the common glob-style patterns 'CVS', '.*' and '*~'.")),
make_option('--no-wrap', action='store_true', dest='no_wrap',
- default=False, help="Don't break long message lines into several lines"),
+ default=False, help=_("Don't break long message lines into several lines")),
make_option('--no-location', action='store_true', dest='no_location',
- default=False, help="Don't write '#: filename:line' lines"),
+ default=False, help=_("Don't write '#: filename:line' lines")),
make_option('--no-obsolete', action='store_true', dest='no_obsolete',
- default=False, help="Remove obsolete message strings"),
+ default=False, help=_("Remove obsolete message strings")),
)
- help = ( "Runs over the entire source tree of the current directory and "
+ help = _( "Runs over the entire source tree of the current directory and "
"pulls out all strings marked for translation. It creates (or updates) a message "
"file in the conf/locale (in the django tree) or locale (for projects and "
"applications) directory.\n\nYou must run this command with one of either the "
@@ -363,7 +364,7 @@ def handle_noargs(self, *args, **options):
extensions = handle_extensions(extensions or ['html', 'txt'])
if verbosity > 1:
- sys.stdout.write('examining files with the extensions: %s\n'
- % get_text_list(list(extensions), 'and'))
+ sys.stdout.write(_('examining files with the extensions: %s\n')
+ % get_text_list(list(extensions), _('and')))
make_messages(locale, domain, verbosity, process_all, extensions, symlinks, ignore_patterns, no_wrap, no_location, no_obsolete)
View
25 django/core/management/commands/reset.py
@@ -4,16 +4,17 @@
from django.core.management.color import no_style
from django.core.management.sql import sql_reset
from django.db import connections, transaction, DEFAULT_DB_ALIAS
+from django.utils.translation import ugettext as _
class Command(AppCommand):
option_list = AppCommand.option_list + (
make_option('--noinput', action='store_false', dest='interactive', default=True,
- help='Tells Django to NOT prompt the user for input of any kind.'),
+ help=_('Tells Django to NOT prompt the user for input of any kind.')),
make_option('--database', action='store', dest='database',
- default=DEFAULT_DB_ALIAS, help='Nominates a database to reset. '
- 'Defaults to the "default" database.'),
+ default=DEFAULT_DB_ALIAS, help=_('Nominates a database to reset. '
+ 'Defaults to the "default" database.')),
)
- help = "Executes ``sqlreset`` for the given app(s) in the current database."
+ help = _("Executes ``sqlreset`` for the given app(s) in the current database.")
args = '[appname ...]'
output_transaction = True
@@ -22,7 +23,7 @@ def handle_app(self, app, **options):
# This command breaks a lot and should be deprecated
import warnings
warnings.warn(
- 'This command has been deprecated. The command ``flush`` can be used to delete everything. You can also use ALTER TABLE or DROP TABLE statements manually.',
+ _('This command has been deprecated. The command ``flush`` can be used to delete everything. You can also use ALTER TABLE or DROP TABLE statements manually.'),
DeprecationWarning
)
using = options.get('database', DEFAULT_DB_ALIAS)
@@ -34,13 +35,13 @@ def handle_app(self, app, **options):
sql_list = sql_reset(app, self.style, connection)
if options.get('interactive'):
- confirm = raw_input("""
+ confirm = raw_input(_("""
You have requested a database reset.
This will IRREVERSIBLY DESTROY any data for
-the "%s" application in the database "%s".
+the "%(app_name)s" application in the database "%(connection_name)s".
Are you sure you want to do this?
-Type 'yes' to continue, or 'no' to cancel: """ % (app_name, connection.settings_dict['NAME']))
+Type 'yes' to continue, or 'no' to cancel: """) % {'app_name': app_name, 'connection_name': connection.settings_dict['NAME']})
else:
confirm = 'yes'
@@ -51,12 +52,12 @@ def handle_app(self, app, **options):
cursor.execute(sql)
except Exception, e:
transaction.rollback_unless_managed()
- raise CommandError("""Error: %s couldn't be reset. Possible reasons:
+ raise CommandError(_("""Error: %(app_name)s couldn't be reset. Possible reasons:
* The database isn't running or isn't configured correctly.
* At least one of the database tables doesn't exist.
* The SQL was invalid.
-Hint: Look at the output of 'django-admin.py sqlreset %s'. That's the SQL this command wasn't able to run.
-The full error: %s""" % (app_name, app_name, e))
+Hint: Look at the output of 'django-admin.py sqlreset %(app_name)s'. That's the SQL this command wasn't able to run.
+The full error: %(error)s""") % {'app_name': app_name, 'error': e})
transaction.commit_unless_managed()
else:
- print "Reset cancelled."
+ print _("Reset cancelled.")
View
3  django/core/management/commands/runfcgi.py
@@ -1,7 +1,8 @@
from django.core.management.base import BaseCommand
+from django.utils.translation import ugettext as _
class Command(BaseCommand):
- help = "Runs this project as a FastCGI application. Requires flup."
+ help = _("Runs this project as a FastCGI application. Requires flup.")
args = '[various KEY=val options, use `runfcgi help` for help]'
def handle(self, *args, **options):
View
35 django/core/management/commands/runserver.py
@@ -7,6 +7,7 @@
from django.core.management.base import BaseCommand, CommandError
from django.core.servers.basehttp import AdminMediaHandler, run, WSGIServerException, get_internal_wsgi_application
from django.utils import autoreload
+from django.utils.translation import ugettext as _
naiveip_re = re.compile(r"""^(?:
(?P<addr>
@@ -20,13 +21,13 @@
class BaseRunserverCommand(BaseCommand):
option_list = BaseCommand.option_list + (
make_option('--ipv6', '-6', action='store_true', dest='use_ipv6', default=False,
- help='Tells Django to use a IPv6 address.'),
+ help=_('Tells Django to use a IPv6 address.')),
make_option('--nothreading', action='store_false', dest='use_threading', default=True,
- help='Tells Django to NOT use threading.'),
+ help=_('Tells Django to NOT use threading.')),
make_option('--noreload', action='store_false', dest='use_reloader', default=True,
- help='Tells Django to NOT use the auto-reloader.'),
+ help=_('Tells Django to NOT use the auto-reloader.')),
)
- help = "Starts a lightweight Web server for development."
+ help = _("Starts a lightweight Web server for development.")
args = '[optional port number, or ipaddr:port]'
# Validation is called explicitly each time the server is reloaded.
@@ -41,9 +42,9 @@ def get_handler(self, *args, **options):
def handle(self, addrport='', *args, **options):
self.use_ipv6 = options.get('use_ipv6')
if self.use_ipv6 and not socket.has_ipv6:
- raise CommandError('Your Python does not support IPv6.')
+ raise CommandError(_('Your Python does not support IPv6.'))
if args:
- raise CommandError('Usage is runserver %s' % self.args)
+ raise CommandError(_('Usage is runserver %s') % self.args)
self._raw_ipv6 = False
if not addrport:
self.addr = ''
@@ -51,18 +52,18 @@ def handle(self, addrport='', *args, **options):
else:
m = re.match(naiveip_re, addrport)
if m is None:
- raise CommandError('"%s" is not a valid port number '
- 'or address:port pair.' % addrport)
+ raise CommandError(_('"%s" is not a valid port number '
+ 'or address:port pair.') % addrport)
self.addr, _ipv4, _ipv6, _fqdn, self.port = m.groups()
if not self.port.isdigit():
- raise CommandError("%r is not a valid port number." % self.port)
+ raise CommandError(_("%r is not a valid port number.") % self.port)
if self.addr:
if _ipv6:
self.addr = self.addr[1:-1]
self.use_ipv6 = True
self._raw_ipv6 = True
elif self.use_ipv6 and not _fqdn:
- raise CommandError('"%s" is not a valid IPv6 address.' % self.addr)
+ raise CommandError(_('"%s" is not a valid IPv6 address.') % self.addr)
if not self.addr:
self.addr = self.use_ipv6 and '::1' or '127.0.0.1'
self._raw_ipv6 = bool(self.use_ipv6)
@@ -87,9 +88,9 @@ def inner_run(self, *args, **options):
shutdown_message = options.get('shutdown_message', '')
quit_command = (sys.platform == 'win32') and 'CTRL-BREAK' or 'CONTROL-C'
- self.stdout.write("Validating models...\n\n")
+ self.stdout.write(_("Validating models...\n\n"))
self.validate(display_num_errors=True)
- self.stdout.write((
+ self.stdout.write(_(
"Django version %(version)s, using settings %(settings)r\n"
"Development server is running at http://%(addr)s:%(port)s/\n"
"Quit the server with %(quit_command)s.\n"
@@ -112,15 +113,15 @@ def inner_run(self, *args, **options):
except WSGIServerException, e:
# Use helpful error messages instead of ugly tracebacks.
ERRORS = {
- 13: "You don't have permission to access that port.",
- 98: "That port is already in use.",
- 99: "That IP address can't be assigned-to.",
+ 13: _("You don't have permission to access that port."),
+ 98: _("That port is already in use."),
+ 99: _("That IP address can't be assigned-to."),
}
try:
error_text = ERRORS[e.args[0].args[0]]
except (AttributeError, KeyError):
error_text = str(e)
- sys.stderr.write(self.style.ERROR("Error: %s" % error_text) + '\n')
+ sys.stderr.write(self.style.ERROR(_("Error: %s") % error_text) + '\n')
# Need to use an OS exit because sys.exit doesn't work in a thread
os._exit(1)
except KeyboardInterrupt:
@@ -131,7 +132,7 @@ def inner_run(self, *args, **options):
class Command(BaseRunserverCommand):
option_list = BaseRunserverCommand.option_list + (
make_option('--adminmedia', dest='admin_media_path', default='',
- help='Specifies the directory from which to serve admin media.'),
+ help=_('Specifies the directory from which to serve admin media.')),
)
def get_handler(self, *args, **options):
View
5 django/core/management/commands/shell.py
@@ -1,13 +1,14 @@
import os
from django.core.management.base import NoArgsCommand
from optparse import make_option
+from django.utils.translation import ugettext as _
class Command(NoArgsCommand):
option_list = NoArgsCommand.option_list + (
make_option('--plain', action='store_true', dest='plain',
- help='Tells Django to use plain Python, not IPython.'),
+ help=_('Tells Django to use plain Python, not IPython.')),
)
- help = "Runs a Python interactive interpreter. Tries to use IPython, if it's available."
+ help = _("Runs a Python interactive interpreter. Tries to use IPython, if it's available.")
shells = ['ipython', 'bpython']
requires_model_validation = False
View
7 django/core/management/commands/sql.py
@@ -3,14 +3,15 @@
from django.core.management.base import AppCommand
from django.core.management.sql import sql_create
from django.db import connections, DEFAULT_DB_ALIAS
+from django.utils.translation import ugettext as _
class Command(AppCommand):
- help = "Prints the CREATE TABLE SQL statements for the given app name(s)."
+ help = _("Prints the CREATE TABLE SQL statements for the given app name(s).")
option_list = AppCommand.option_list + (
make_option('--database', action='store', dest='database',
- default=DEFAULT_DB_ALIAS, help='Nominates a database to print the '
- 'SQL for. Defaults to the "default" database.'),
+ default=DEFAULT_DB_ALIAS, help=_('Nominates a database to print the '
+ 'SQL for. Defaults to the "default" database.')),
)
output_transaction = True
View
7 django/core/management/commands/sqlall.py
@@ -3,14 +3,15 @@
from django.core.management.base import AppCommand
from django.core.management.sql import sql_all
from django.db import connections, DEFAULT_DB_ALIAS
+from django.utils.translation import ugettext as _
class Command(AppCommand):
- help = "Prints the CREATE TABLE, custom SQL and CREATE INDEX SQL statements for the given model module name(s)."
+ help = _("Prints the CREATE TABLE, custom SQL and CREATE INDEX SQL statements for the given model module name(s).")
option_list = AppCommand.option_list + (
make_option('--database', action='store', dest='database',
- default=DEFAULT_DB_ALIAS, help='Nominates a database to print the '
- 'SQL for. Defaults to the "default" database.'),
+ default=DEFAULT_DB_ALIAS, help=_('Nominates a database to print the '
+ 'SQL for. Defaults to the "default" database.')),
)
output_transaction = True
View
7 django/core/management/commands/sqlclear.py
@@ -3,14 +3,15 @@
from django.core.management.base import AppCommand
from django.core.management.sql import sql_delete
from django.db import connections, DEFAULT_DB_ALIAS
+from django.utils.translation import ugettext as _
class Command(AppCommand):
- help = "Prints the DROP TABLE SQL statements for the given app name(s)."
+ help = _("Prints the DROP TABLE SQL statements for the given app name(s).")
option_list = AppCommand.option_list + (
make_option('--database', action='store', dest='database',
- default=DEFAULT_DB_ALIAS, help='Nominates a database to print the '
- 'SQL for. Defaults to the "default" database.'),
+ default=DEFAULT_DB_ALIAS, help=_('Nominates a database to print the '
+ 'SQL for. Defaults to the "default" database.')),
)
output_transaction = True
View
7 django/core/management/commands/sqlcustom.py
@@ -3,14 +3,15 @@
from django.core.management.base import AppCommand
from django.core.management.sql import sql_custom
from django.db import connections, DEFAULT_DB_ALIAS
+from django.utils.translation import ugettext as _
class Command(AppCommand):
- help = "Prints the custom table modifying SQL statements for the given app name(s)."
+ help = _("Prints the custom table modifying SQL statements for the given app name(s).")
option_list = AppCommand.option_list + (
make_option('--database', action='store', dest='database',
- default=DEFAULT_DB_ALIAS, help='Nominates a database to print the '
- 'SQL for. Defaults to the "default" database.'),
+ default=DEFAULT_DB_ALIAS, help=_('Nominates a database to print the '
+ 'SQL for. Defaults to the "default" database.')),
)
output_transaction = True
View
7 django/core/management/commands/sqlflush.py
@@ -3,14 +3,15 @@
from django.core.management.base import NoArgsCommand
from django.core.management.sql import sql_flush
from django.db import connections, DEFAULT_DB_ALIAS
+from django.utils.translation import ugettext as _
class Command(NoArgsCommand):
- help = "Returns a list of the SQL statements required to return all tables in the database to the state they were in just after they were installed."
+ help = _("Returns a list of the SQL statements required to return all tables in the database to the state they were in just after they were installed.")
option_list = NoArgsCommand.option_list + (
make_option('--database', action='store', dest='database',
- default=DEFAULT_DB_ALIAS, help='Nominates a database to print the '
- 'SQL for. Defaults to the "default" database.'),
+ default=DEFAULT_DB_ALIAS, help=_('Nominates a database to print the '
+ 'SQL for. Defaults to the "default" database.')),
)
output_transaction = True
View
7 django/core/management/commands/sqlindexes.py
@@ -3,14 +3,15 @@
from django.core.management.base import AppCommand
from django.core.management.sql import sql_indexes
from django.db import connections, DEFAULT_DB_ALIAS
+from django.utils.translation import ugettext as _
class Command(AppCommand):
- help = "Prints the CREATE INDEX SQL statements for the given model module name(s)."
+ help = _("Prints the CREATE INDEX SQL statements for the given model module name(s).")
option_list = AppCommand.option_list + (
make_option('--database', action='store', dest='database',
- default=DEFAULT_DB_ALIAS, help='Nominates a database to print the '
- 'SQL for. Defaults to the "default" database.'),
+ default=DEFAULT_DB_ALIAS, help=_('Nominates a database to print the '
+ 'SQL for. Defaults to the "default" database.')),
)
View
5 django/core/management/commands/sqlinitialdata.py
@@ -1,7 +1,8 @@
from django.core.management.base import AppCommand, CommandError
+from django.utils.translation import ugettext as _
class Command(AppCommand):
- help = "RENAMED: see 'sqlcustom'"
+ help = _("RENAMED: see 'sqlcustom'")
def handle(self, *apps, **options):
- raise CommandError("This command has been renamed. Use the 'sqlcustom' command instead.")
+ raise CommandError(_("This command has been renamed. Use the 'sqlcustom' command instead."))
View
7 django/core/management/commands/sqlreset.py
@@ -3,14 +3,15 @@
from django.core.management.base import AppCommand
from django.core.management.sql import sql_reset
from django.db import connections, DEFAULT_DB_ALIAS
+from django.utils.translation import ugettext as _
class Command(AppCommand):
- help = "Prints the DROP TABLE SQL, then the CREATE TABLE SQL, for the given app name(s)."
+ help = _("Prints the DROP TABLE SQL, then the CREATE TABLE SQL, for the given app name(s).")
option_list = AppCommand.option_list + (
make_option('--database', action='store', dest='database',
- default=DEFAULT_DB_ALIAS, help='Nominates a database to print the '
- 'SQL for. Defaults to the "default" database.'),
+ default=DEFAULT_DB_ALIAS, help=_('Nominates a database to print the '
+ 'SQL for. Defaults to the "default" database.')),
)
View
7 django/core/management/commands/sqlsequencereset.py
@@ -2,14 +2,15 @@
from django.core.management.base import AppCommand
from django.db import connections, models, DEFAULT_DB_ALIAS
+from django.utils.translation import ugettext as _
class Command(AppCommand):
- help = 'Prints the SQL statements for resetting sequences for the given app name(s).'
+ help = _('Prints the SQL statements for resetting sequences for the given app name(s).')
option_list = AppCommand.option_list + (
make_option('--database', action='store', dest='database',
- default=DEFAULT_DB_ALIAS, help='Nominates a database to print the '
- 'SQL for. Defaults to the "default" database.'),
+ default=DEFAULT_DB_ALIAS, help=_('Nominates a database to print the '
+ 'SQL for. Defaults to the "default" database.')),
)
View
5 django/core/management/commands/startapp.py
@@ -2,9 +2,10 @@
from django.core.management.base import copy_helper, CommandError, LabelCommand
from django.utils.importlib import import_module
+from django.utils.translation import ugettext as _
class Command(LabelCommand):
- help = "Creates a Django app directory structure for the given app name in the current directory."
+ help = _("Creates a Django app directory structure for the given app name in the current directory.")
args = "[appname]"
label = 'application name'
@@ -23,6 +24,6 @@ def handle_label(self, app_name, directory=None, **options):
except ImportError:
pass
else:
- raise CommandError("%r conflicts with the name of an existing Python module and cannot be used as an app name. Please try another name." % app_name)
+ raise CommandError(_("%r conflicts with the name of an existing Python module and cannot be used as an app name. Please try another name.") % app_name)
copy_helper(self.style, 'app', app_name, directory)
View
5 django/core/management/commands/startproject.py
@@ -1,11 +1,12 @@
from django.core.management.base import copy_helper, CommandError, LabelCommand
from django.utils.importlib import import_module
+from django.utils.translation import ugettext as _
import os
import re
from random import choice
class Command(LabelCommand):
- help = "Creates a Django project directory structure for the given project name in the current directory."
+ help = _("Creates a Django project directory structure for the given project name in the current directory.")
args = "[projectname]"
label = 'project name'
@@ -23,7 +24,7 @@ def handle_label(self, project_name, **options):
except ImportError:
pass
else:
- raise CommandError("%r conflicts with the name of an existing Python module and cannot be used as a project name. Please try another name." % project_name)
+ raise CommandError(_("%r conflicts with the name of an existing Python module and cannot be used as a project name. Please try another name.") % project_name)
copy_helper(self.style, 'project', project_name, directory)
View
33 django/core/management/commands/syncdb.py
@@ -8,17 +8,18 @@
from django.db import connections, router, transaction, models, DEFAULT_DB_ALIAS
from django.utils.datastructures import SortedDict
from django.utils.importlib import import_module
+from django.utils.translation import ugettext as _
class Command(NoArgsCommand):
option_list = NoArgsCommand.option_list + (
make_option('--noinput', action='store_false', dest='interactive', default=True,
- help='Tells Django to NOT prompt the user for input of any kind.'),
+ help=_('Tells Django to NOT prompt the user for input of any kind.')),
make_option('--database', action='store', dest='database',
- default=DEFAULT_DB_ALIAS, help='Nominates a database to synchronize. '
- 'Defaults to the "default" database.'),
+ default=DEFAULT_DB_ALIAS, help=_('Nominates a database to synchronize. '
+ 'Defaults to the "default" database.')),
)
- help = "Create the database tables for all apps in INSTALLED_APPS whose tables haven't already been created."
+ help = _("Create the database tables for all apps in INSTALLED_APPS whose tables haven't already been created.")
def handle_noargs(self, **options):
@@ -81,12 +82,12 @@ def model_installed(model):
# Create the tables for each model
if verbosity >= 1:
- print "Creating tables ..."
+ print _("Creating tables ...")
for app_name, model_list in manifest.items():
for model in model_list:
# Create the model's database table, if it doesn't already exist.
if verbosity >= 3:
- print "Processing %s.%s model" % (app_name, model._meta.object_name)
+ print _("Processing %(app_name)s.%(model)s model") % {'app_name': app_name, 'model': model._meta.object_name}
sql, references = connection.creation.sql_create_model(model, self.style, seen_models)
seen_models.add(model)
created_models.add(model)
@@ -96,7 +97,7 @@ def model_installed(model):
sql.extend(connection.creation.sql_for_pending_references(refto, self.style, pending_references))
sql.extend(connection.creation.sql_for_pending_references(model, self.style, pending_references))
if verbosity >= 1 and sql:
- print "Creating table %s" % model._meta.db_table
+ print _("Creating table %s") % model._meta.db_table
for statement in sql:
cursor.execute(statement)
tables.append(connection.introspection.table_name_converter(model._meta.db_table))
@@ -114,20 +115,20 @@ def model_installed(model):
# Install custom SQL for the app (but only if this
# is a model we've just created)
if verbosity >= 1:
- print "Installing custom SQL ..."
+ print _("Installing custom SQL ...")
for app_name, model_list in manifest.items():
for model in model_list:
if model in created_models:
custom_sql = custom_sql_for_model(model, self.style, connection)
if custom_sql:
if verbosity >= 2:
- print "Installing custom SQL for %s.%s model" % (app_name, model._meta.object_name)
+ print _("Installing custom SQL for %(app_name)s.%(model)s model") % {'app_name': app_name, 'model': model._meta.object_name}
try:
for sql in custom_sql:
cursor.execute(sql)
except Exception, e:
- sys.stderr.write("Failed to install custom SQL for %s.%s model: %s\n" % \
- (app_name, model._meta.object_name, e))
+ sys.stderr.write(_("Failed to install custom SQL for %(app_name)s.%(model)s model: %(error)s\n") % \
+ {'app_name': app_name, 'model': model._meta.object_name, 'error': e})
if show_traceback:
import traceback
traceback.print_exc()
@@ -136,10 +137,10 @@ def model_installed(model):
transaction.commit_unless_managed(using=db)
else:
if verbosity >= 3:
- print "No custom SQL for %s.%s model" % (app_name, model._meta.object_name)
+ print _("No custom SQL for %(app_name)s.%(model)s model") % {'app_name': app_name, 'model': model._meta.object_name}
if verbosity >= 1:
- print "Installing indexes ..."
+ print _("Installing indexes ...")
# Install SQL indices for all newly created models
for app_name, model_list in manifest.items():
for model in model_list:
@@ -147,13 +148,13 @@ def model_installed(model):
index_sql = connection.creation.sql_indexes_for_model(model, self.style)
if index_sql:
if verbosity >= 2:
- print "Installing index for %s.%s model" % (app_name, model._meta.object_name)
+ print _("Installing index for %(app_name)s.%(model)s model") % {'app_name': app_name, 'model': model._meta.object_name}
try:
for sql in index_sql:
cursor.execute(sql)
except Exception, e:
- sys.stderr.write("Failed to install index for %s.%s model: %s\n" % \
- (app_name, model._meta.object_name, e))
+ sys.stderr.write(_("Failed to install index for %(app_name)s.%(model)s model: %(error)s\n") % \
+ {'app_name': app_name, 'model': model._meta.object_name, 'error': e})
transaction.rollback_unless_managed(using=db)
else:
transaction.commit_unless_managed(using=db)
View
11 django/core/management/commands/test.py
@@ -3,18 +3,19 @@
from optparse import make_option, OptionParser
import sys
from django.test.utils import get_runner
+from django.utils.translation import ugettext as _
class Command(BaseCommand):
option_list = BaseCommand.option_list + (
make_option('--noinput', action='store_false', dest='interactive', default=True,
- help='Tells Django to NOT prompt the user for input of any kind.'),
+ help=_('Tells Django to NOT prompt the user for input of any kind.')),
make_option('--failfast', action='store_true', dest='failfast', default=False,
- help='Tells Django to stop running the test suite after first failed test.'),
+ help=_('Tells Django to stop running the test suite after first failed test.')),
make_option('--testrunner', action='store', dest='testrunner',
- help='Tells Django to use specified test runner class instead of the one '+
- 'specified by the TEST_RUNNER setting.')
+ help=_('Tells Django to use specified test runner class instead of the one '+
+ 'specified by the TEST_RUNNER setting.'))
)
- help = 'Runs the test suite for the specified applications, or the entire site if no apps are specified.'
+ help = _('Runs the test suite for the specified applications, or the entire site if no apps are specified.')
args = '[appname ...]'
requires_model_validation = False
View
11 django/core/management/commands/testserver.py
@@ -1,18 +1,19 @@
from django.core.management.base import BaseCommand
+from django.utils.translation import ugettext as _
from optparse import make_option
class Command(BaseCommand):
option_list = BaseCommand.option_list + (
make_option('--noinput', action='store_false', dest='interactive', default=True,
- help='Tells Django to NOT prompt the user for input of any kind.'),
+ help=_('Tells Django to NOT prompt the user for input of any kind.')),
make_option('--addrport', action='store', dest='addrport',
type='string', default='',
- help='port number or ipaddr:port to run the server on'),
+ help=_('port number or ipaddr:port to run the server on')),
make_option('--ipv6', '-6', action='store_true', dest='use_ipv6', default=False,
- help='Tells Django to use a IPv6 address.'),
+ help=_('Tells Django to use a IPv6 address.')),
)
- help = 'Runs a development server with data from the given fixture(s).'
+ help = _('Runs a development server with data from the given fixture(s).')
args = '[fixture ...]'
requires_model_validation = False
@@ -34,5 +35,5 @@ def handle(self, *fixture_labels, **options):
# Run the development server. Turn off auto-reloading because it causes
# a strange error -- it causes this handle() method to be called
# multiple times.
- shutdown_message = '\nServer stopped.\nNote that the test database, %r, has not been deleted. You can explore it on your own.' % db_name
+ shutdown_message = _('\nServer stopped.\nNote that the test database, %r, has not been deleted. You can explore it on your own.') % db_name
call_command('runserver', addrport=addrport, shutdown_message=shutdown_message, use_reloader=False, use_ipv6=options['use_ipv6'])
View
3  django/core/management/commands/validate.py
@@ -1,7 +1,8 @@
from django.core.management.base import NoArgsCommand
+from django.utils.translation import ugettext as _
class Command(NoArgsCommand):
- help = "Validates all installed models."
+ help = _("Validates all installed models.")
requires_model_validation = False
View
9 django/core/management/sql.py
@@ -5,6 +5,7 @@
from django.core.management.base import CommandError
from django.db import models
from django.db.models import get_models
+from django.utils.translation import ugettext as _
def sql_create(app, style, connection):
"Returns a list of the CREATE TABLE SQL statements for the given app."
@@ -12,10 +13,10 @@ def sql_create(app, style, connection):
if connection.settings_dict['ENGINE'] == 'django.db.backends.dummy':
# This must be the "dummy" database backend, which means the user
# hasn't set ENGINE for the database.
- raise CommandError("Django doesn't know which syntax to use for your SQL statements,\n" +
+ raise CommandError(_("Django doesn't know which syntax to use for your SQL statements,\n" +
"because you haven't specified the ENGINE setting for the database.\n" +
"Edit your settings file and change DATBASES['default']['ENGINE'] to something like\n" +
- "'django.db.backends.postgresql' or 'django.db.backends.mysql'.")
+ "'django.db.backends.postgresql' or 'django.db.backends.mysql'."))
# Get installed models, so we generate REFERENCES right.
# We trim models from the current app so that the sqlreset command does not
@@ -101,7 +102,7 @@ def sql_reset(app, style, connection):
# This command breaks a lot and should be deprecated
import warnings
warnings.warn(
- 'This command has been deprecated. The command ``sqlflush`` can be used to delete everything. You can also use ALTER TABLE or DROP TABLE statements manually.',
+ _('This command has been deprecated. The command ``sqlflush`` can be used to delete everything. You can also use ALTER TABLE or DROP TABLE statements manually.'),
DeprecationWarning
)
return sql_delete(app, style, connection) + sql_all(app, style, connection)
@@ -183,7 +184,7 @@ def emit_post_sync_signal(created_models, verbosity, interactive, db):
for app in models.get_apps():
app_name = app.__name__.split('.')[-2]
if verbosity >= 2:
- print "Running post-sync handlers for application", app_name
+ print _("Running post-sync handlers for application"), app_name
models.signals.post_syncdb.send(sender=app, app=app,
created_models=created_models, verbosity=verbosity,
interactive=interactive, db=db)
View
151 django/core/management/validation.py
@@ -2,6 +2,7 @@
from django.core.management.color import color_style
from django.utils.itercompat import is_iterable
+from django.utils.translation import ugettext as _
class ModelErrorCollection:
def __init__(self, outfile=sys.stdout):
@@ -36,25 +37,25 @@ def get_validation_errors(outfile, app=None):
# Do field-specific validation.
for f in opts.local_fields:
if f.name == 'id' and not f.primary_key and opts.pk.name == 'id':
- e.add(opts, '"%s": You can\'t use "id" as a field name, because each model automatically gets an "id" field if none of the fields have primary_key=True. You need to either remove/rename your "id" field or add primary_key=True to a field.' % f.name)
+ e.add(opts, _('"%s": You can\'t use "id" as a field name, because each model automatically gets an "id" field if none of the fields have primary_key=True. You need to either remove/rename your "id" field or add primary_key=True to a field.') % f.name)
if f.name.endswith('_'):
- e.add(opts, '"%s": Field names cannot end with underscores, because this would lead to ambiguous queryset filters.' % f.name)
+ e.add(opts, _('"%s": Field names cannot end with underscores, because this would lead to ambiguous queryset filters.') % f.name)
if (f.primary_key and f.null and
not connection.features.interprets_empty_strings_as_nulls):
# We cannot reliably check this for backends like Oracle which
# consider NULL and '' to be equal (and thus set up
# character-based fields a little differently).
- e.add(opts, '"%s": Primary key fields cannot have null=True.' % f.name)
+ e.add(opts, _('"%s": Primary key fields cannot have null=True.') % f.name)
if isinstance(f, models.CharField):
try:
max_length = int(f.max_length)
if max_length <= 0:
- e.add(opts, '"%s": CharFields require a "max_length" attribute that is a positive integer.' % f.name)
+ e.add(opts, _('"%s": CharFields require a "max_length" attribute that is a positive integer.') % f.name)
except (ValueError, TypeError):
- e.add(opts, '"%s": CharFields require a "max_length" attribute that is a positive integer.' % f.name)
+ e.add(opts, _('"%s": CharFields require a "max_length" attribute that is a positive integer.') % f.name)
if isinstance(f, models.DecimalField):
decimalp_ok, mdigits_ok = False, False
- decimalp_msg ='"%s": DecimalFields require a "decimal_places" attribute that is a non-negative integer.'
+ decimalp_msg =_('"%s": DecimalFields require a "decimal_places" attribute that is a non-negative integer.')
try:
decimal_places = int(f.decimal_places)
if decimal_places < 0:
@@ -63,7 +64,7 @@ def get_validation_errors(outfile, app=None):
decimalp_ok = True
except (ValueError, TypeError):
e.add(opts, decimalp_msg % f.name)
- mdigits_msg = '"%s": DecimalFields require a "max_digits" attribute that is a positive integer.'
+ mdigits_msg = _('"%s": DecimalFields require a "max_digits" attribute that is a positive integer.')
try:
max_digits = int(f.max_digits)
if max_digits <= 0:
@@ -72,12 +73,12 @@ def get_validation_errors(outfile, app=None):
mdigits_ok = True
except (ValueError, TypeError):
e.add(opts, mdigits_msg % f.name)
- invalid_values_msg = '"%s": DecimalFields require a "max_digits" attribute value that is greater than or equal to the value of the "decimal_places" attribute.'
+ invalid_values_msg = _('"%s": DecimalFields require a "max_digits" attribute value that is greater than or equal to the value of the "decimal_places" attribute.')
if decimalp_ok and mdigits_ok:
if decimal_places > max_digits:
e.add(opts, invalid_values_msg % f.name)
if isinstance(f, models.FileField) and not f.upload_to:
- e.add(opts, '"%s": FileFields require an "upload_to" attribute.' % f.name)
+ e.add(opts, _('"%s": FileFields require an "upload_to" attribute.') % f.name)
if isinstance(f, models.ImageField):
# Try to import PIL in either of the two ways it can end up installed.
try:
@@ -86,18 +87,18 @@ def get_validation_errors(outfile, app=None):
try:
import Image
except ImportError:
- e.add(opts, '"%s": To use ImageFields, you need to install the Python Imaging Library. Get it at http://www.pythonware.com/products/pil/ .' % f.name)
+ e.add(opts, _('"%s": To use ImageFields, you need to install the Python Imaging Library. Get it at http://www.pythonware.com/products/pil/ .') % f.name)
if isinstance(f, models.BooleanField) and getattr(f, 'null', False):
- e.add(opts, '"%s": BooleanFields do not accept null values. Use a NullBooleanField instead.' % f.name)
+ e.add(opts, _('"%s": BooleanFields do not accept null values. Use a NullBooleanField instead.') % f.name)
if f.choices:
if isinstance(f.choices, basestring) or not is_iterable(f.choices):
- e.add(opts, '"%s": "choices" should be iterable (e.g., a tuple or list).' % f.name)
+ e.add(opts, _('"%s": "choices" should be iterable (e.g., a tuple or list).') % f.name)
else:
for c in f.choices:
if not isinstance(c, (list, tuple)) or len(c) != 2:
- e.add(opts, '"%s": "choices" should be a sequence of two-tuples.' % f.name)
+ e.add(opts, _('"%s": "choices" should be a sequence of two-tuples.') % f.name)
if f.db_index not in (None, True, False):
- e.add(opts, '"%s": "db_index" should be either None, True or False.' % f.name)
+ e.add(opts, _('"%s": "db_index" should be either None, True or False.') % f.name)
# Perform any backend-specific field validation.
connection.validation.validate_field(e, opts, f)
@@ -105,15 +106,15 @@ def get_validation_errors(outfile, app=None):
# Check if the on_delete behavior is sane
if f.rel and hasattr(f.rel, 'on_delete'):
if f.rel.on_delete == SET_NULL and not f.null:
- e.add(opts, "'%s' specifies on_delete=SET_NULL, but cannot be null." % f.name)
+ e.add(opts, _("'%s' specifies on_delete=SET_NULL, but cannot be null.") % f.name)
elif f.rel.on_delete == SET_DEFAULT and not f.has_default():
- e.add(opts, "'%s' specifies on_delete=SET_DEFAULT, but has no default value." % f.name)
+ e.add(opts, _("'%s' specifies on_delete=SET_DEFAULT, but has no default value.") % f.name)
# Check to see if the related field will clash with any existing
# fields, m2m fields, m2m related objects or related objects
if f.rel:
if f.rel.to not in models.get_models():
- e.add(opts, "'%s' has a relation with model %s, which has either not been installed or is abstract." % (f.name, f.rel.to))
+ e.add(opts, _("'%(name)s' has a relation with model %(relto)s, which has either not been installed or is abstract.") % {'name': f.name, 'relto': f.rel.to})
# it is a string and we could not find the model it refers to
# so skip the next section
if isinstance(f.rel.to, (str, unicode)):
@@ -121,7 +122,7 @@ def get_validation_errors(outfile, app=None):
# Make sure the related field specified by a ForeignKey is unique
if not f.rel.to._meta.get_field(f.rel.field_name).unique:
- e.add(opts, "Field '%s' under model '%s' must have a unique=True constraint." % (f.rel.field_name, f.rel.to.__name__))
+ e.add(opts, _("Field '%(field_name)s' under model '%(reltoname)s' must have a unique=True constraint.") % {'field_name': f.rel.field_name, 'reltoname': f.rel.to.__name__})
rel_opts = f.rel.to._meta
rel_name = RelatedObject(f.rel.to, cls, f).get_accessor_name()
@@ -129,25 +130,25 @@ def get_validation_errors(outfile, app=None):
if not f.rel.is_hidden():
for r in rel_opts.fields:
if r.name == rel_name:
- e.add(opts, "Accessor for field '%s' clashes with field '%s.%s'. Add a related_name argument to the definition for '%s'." % (f.name, rel_opts.object_name, r.name, f.name))
+ e.add(opts, _("Accessor for field '%(fname)s' clashes with field '%(object_name)s.%(rname)s'. Add a related_name argument to the definition for '%(fname)s'.") % {'fname': f.name, 'object_name': rel_opts.object_name, 'rname': r.name})
if r.name == rel_query_name:
- e.add(opts, "Reverse query name for field '%s' clashes with field '%s.%s'. Add a related_name argument to the definition for '%s'." % (f.name, rel_opts.object_name, r.name, f.name))
+ e.add(opts, _("Reverse query name for field '%(fname)s' clashes with field '%(object_name)s.%(rname)s'. Add a related_name argument to the definition for '%(fname)s'.") % {'fname': f.name, 'object_name': rel_opts.object_name, 'rname': r.name})
for r in rel_opts.local_many_to_many:
if r.name == rel_name:
- e.add(opts, "Accessor for field '%s' clashes with m2m field '%s.%s'. Add a related_name argument to the definition for '%s'." % (f.name, rel_opts.object_name, r.name, f.name))
+ e.add(opts, _("Accessor for field '%(fname)s' clashes with m2m field '%(object_name)s.%(rname)s'. Add a related_name argument to the definition for '%(object_name)s'.") % {'fname': f.name, 'object_name': rel_opts.object_name, 'rname': r.name})
if r.name == rel_query_name:
- e.add(opts, "Reverse query name for field '%s' clashes with m2m field '%s.%s'. Add a related_name argument to the definition for '%s'." % (f.name, rel_opts.object_name, r.name, f.name))
+ e.add(opts, _("Reverse query name for field '%(fname)s' clashes with m2m field '%(object_name)s.%(rname)s'. Add a related_name argument to the definition for '%(object_name)s'.") % {'fname': f.name, 'object_name': rel_opts.object_name, 'rname': r.name})
for r in rel_opts.get_all_related_many_to_many_objects():
if r.get_accessor_name() == rel_name:
- e.add(opts, "Accessor for field '%s' clashes with related m2m field '%s.%s'. Add a related_name argument to the definition for '%s'." % (f.name, rel_opts.object_name, r.get_accessor_name(), f.name))
+ e.add(opts, _("Accessor for field '%(fname)s' clashes with related m2m field '%(object_name)s.%(get_accessor_name)s'. Add a related_name argument to the definition for '%(fname)s'.") % {'fname': f.name, 'object_name': rel_opts.object_name, 'get_accessor_name': r.get_accessor_name()})
if r.get_accessor_name() == rel_query_name:
- e.add(opts, "Reverse query name for field '%s' clashes with related m2m field '%s.%s'. Add a related_name argument to the definition for '%s'." % (f.name, rel_opts.object_name, r.get_accessor_name(), f.name))
+ e.add(opts, _("Reverse query name for field '%(fname)s' clashes with related m2m field '%(object_name)s.%(get_accessor_name)s'. Add a related_name argument to the definition for '%(fname)s'.") % {'fname': f.name, 'object_name': rel_opts.object_name, 'get_accessor_name': r.get_accessor_name()})
for r in rel_opts.get_all_related_objects():
if r.field is not f:
if r.get_accessor_name() == rel_name:
- e.add(opts, "Accessor for field '%s' clashes with related field '%s.%s'. Add a related_name argument to the definition for '%s'." % (f.name, rel_opts.object_name, r.get_accessor_name(), f.name))
+ e.add(opts, _("Accessor for field '%(fname)s' clashes with related field '%(object_name)s.%(get_accessor_name)s'. Add a related_name argument to the definition for '%(fname)s'.") % {'fname': f.name, 'object_name': rel_opts.object_name, 'get_accessor_name': r.get_accessor_name()})
if r.get_accessor_name() == rel_query_name:
- e.add(opts, "Reverse query name for field '%s' clashes with related field '%s.%s'. Add a related_name argument to the definition for '%s'." % (f.name, rel_opts.object_name, r.get_accessor_name(), f.name))
+ e.add(opts, _("Reverse query name for field '%(fname)s' clashes with related field '%(object_name)s.