Ticket #1491: colourful.diff

File colourful.diff, 30.9 KB (added by plmeister@…, 19 years ago)

colour output for django-admin.py

  • termcolors.py

     
     1#!/usr/bin/python
     2
     3"""
     4termcolors.py
     5
     6set termcolors.DISABLE = True to disable the whole shebang
     7"""
     8import types
     9
     10colour_names = ('black', 'red', 'green', 'yellow', 'blue', 'magenta',
     11        'cyan', 'white')
     12foreground = {}; background = {}
     13[ foreground.update({colour_names[x]: '3%s' % x}) for x in range(8) ]
     14[ background.update({colour_names[x]: '4%s' % x}) for x in range(8) ]
     15
     16RESET, BOLD, UNDERSCORE, BLINK, REVERSE, CONCEAL = '014578'
     17opt_dict = {'bold': BOLD, 'underscore': UNDERSCORE, 'blink': BLINK,
     18        'reverse': REVERSE, 'conceal': CONCEAL,}
     19
     20DISABLE = False
     21
     22def gfx(text='', opts=(), **kwargs):
     23    """Returns your text, enclosed in ANSI graphics codes
     24   
     25Depends on the keyword arguments 'fgcol' and 'bgcol', and the contents of the
     26opts tuple/list
     27
     28With no parameters is a special case - it returns the RESET code
     29
     30Valid colours:
     31    'black', 'red', 'green', 'yellow', 'blue', 'magenta', 'cyan', 'white'
     32   
     33Valid options:
     34    'bold'
     35    'underscore'
     36    'blink'
     37    'reverse'
     38    'conceal'
     39    'noreset' - string will not be auto-terminated with the RESET code
     40
     41Examples:
     42    gfx('hello', fgcol='red', bgcol='blue', opts=('blink',))
     43    gfx()
     44    gfx('goodbye', opts=('underscore',))
     45    print gfx('first line', fgcol='red', opts=('noreset',))
     46    print 'this should be red too'
     47    print gfx('and so should this')
     48    print 'this should not be red'
     49"""
     50    text = str(text)
     51    if DISABLE:
     52        return text
     53    code_list = []
     54    if text == '' and len(opts) == 1 and opts[0] == 'reset':
     55        return '\x1b[%sm' % RESET
     56    for k,v in kwargs.iteritems():
     57        if k == 'fgcol':
     58            code_list.append(foreground[v])
     59        elif k == 'bgcol':
     60            code_list.append(background[v])
     61    for o in opts:
     62        if o in opt_dict:
     63            code_list.append(opt_dict[o])
     64    if not ('noreset' in opts):
     65        text = text + '\x1b[%sm' % RESET
     66    return ('\x1b[%sm' % ';'.join(code_list)) + text
     67
     68def make_style(opts=(), **kwargs):
     69    """Returns a function with default parameters for gfx()
     70
     71    Example:
     72        bold_red = make_style(opts=('bold',), fgcol='red')
     73        print bold_red('hello')
     74
     75        KEYWORD = make_style(fgcol='yellow')
     76        COMMENT = make_style(fgcol='blue', opts=('bold',))
     77    etc
     78    """
     79    return lambda text: gfx(text, opts, **kwargs)
     80
     81    result = ''
     82    for a in args:
     83        if a.__class__ in types.StringTypes:
     84            result += a
     85        elif a.__class__ in [types.TupleType, types.ListType]:
     86            result += a[0](a[1])
     87    return result
     88
  • management.py

     
    44import django
    55import os, re, sys, textwrap
    66from optparse import OptionParser
     7import termcolors
    78
     9class dummy:
     10    pass
     11
     12style = dummy()
     13
     14style.ERROR = termcolors.make_style(fgcol='white', bgcol='red', opts=('bold',))
     15style.ERROR_OUTPUT = termcolors.make_style(fgcol='red', opts=('bold',))
     16style.OK = termcolors.make_style(fgcol='green', opts=('bold',))
     17style.SQL_STRING = termcolors.make_style(fgcol='cyan')
     18style.SQL_FIELD = termcolors.make_style(fgcol='green')
     19style.SQL_KEYWORD = termcolors.make_style(fgcol='yellow')
     20style.SQL_NUMBER = style.SQL_STRING
     21style.SQL_TABLE = termcolors.make_style(fgcol='green', opts=('bold',))
     22style.SQL_TRANS = termcolors.make_style(opts=('bold',))
     23
     24def J(*args):
     25    return ''.join(map(str, args))
     26
     27def disable_sql_styles():
     28    l = lambda x: x
     29    style.SQL_STRING = l
     30    style.SQL_FIELD = l
     31    style.SQL_KEYWORD = l
     32    style.SQL_TABLE = l
     33
     34if (not sys.stdout.isatty()) or (sys.platform == 'win32'):
     35    # if somebody's piping our output through to psql or something,
     36    # they might be a touch miffed if it's all full of escape chars
     37    termcolors.DISABLE = True
     38
    839# For Python 2.3
    940if not hasattr(__builtins__, 'set'):
    1041    from sets import Set as set
     
    2758
    2859def _get_packages_insert(app_label):
    2960    from django.core.db import db
    30     return "INSERT INTO %s (%s, %s) VALUES ('%s', '%s');" % \
    31         (db.quote_name('packages'), db.quote_name('label'), db.quote_name('name'),
    32         app_label, app_label)
     61    return J(style.SQL_KEYWORD("INSERT INTO")," %s (%s, %s) ",
     62                   style.SQL_KEYWORD("VALUES")," (%s, %s);") % \
     63        (style.SQL_TABLE(db.quote_name('packages')),
     64         style.SQL_FIELD(db.quote_name('label')),
     65         style.SQL_FIELD(db.quote_name('name')),
     66         style.SQL_STRING("'"+app_label+"'"),
     67         style.SQL_STRING("'"+app_label+"'"))
    3368
    3469def _get_permission_codename(action, opts):
    3570    return '%s_%s' % (action, opts.object_name.lower())
     
    4479
    4580def _get_permission_insert(name, codename, opts):
    4681    from django.core.db import db
    47     return "INSERT INTO %s (%s, %s, %s) VALUES ('%s', '%s', '%s');" % \
    48         (db.quote_name('auth_permissions'), db.quote_name('name'), db.quote_name('package'),
    49         db.quote_name('codename'), name.replace("'", "''"), opts.app_label, codename)
     82    return J(style.SQL_KEYWORD("INSERT INTO")," %s (%s, %s, %s) ",
     83                   style.SQL_KEYWORD("VALUES")," (%s, %s, %s);") % \
     84        (style.SQL_TABLE(db.quote_name('auth_permissions')),
     85         style.SQL_FIELD(db.quote_name('name')),
     86         style.SQL_FIELD(db.quote_name('package')),
     87         style.SQL_FIELD(db.quote_name('codename')),
     88         style.SQL_STRING("'"+name.replace("'", "''")+"'"),
     89         style.SQL_STRING("'"+opts.app_label+"'"),
     90         style.SQL_STRING("'"+codename+"'"))
    5091
    5192def _get_contenttype_insert(opts):
    5293    from django.core.db import db
    53     return "INSERT INTO %s (%s, %s, %s) VALUES ('%s', '%s', '%s');" % \
    54         (db.quote_name('content_types'), db.quote_name('name'), db.quote_name('package'),
    55         db.quote_name('python_module_name'), opts.verbose_name, opts.app_label, opts.module_name)
     94    return J(style.SQL_KEYWORD("INSERT INTO"), " %s (%s, %s, %s) ",
     95                   style.SQL_KEYWORD("VALUES"), " (%s, %s, %s);") % \
     96        (style.SQL_TABLE(db.quote_name('content_types')),
     97         style.SQL_FIELD(db.quote_name('name')),
     98         style.SQL_FIELD(db.quote_name('package')),
     99         style.SQL_FIELD(db.quote_name('python_module_name')),
     100         style.SQL_STRING("'"+opts.verbose_name.__str__()+"'"),
     101         style.SQL_STRING("'"+opts.app_label.__str__()+"'"),
     102         style.SQL_STRING("'"+opts.module_name.__str__()+"'"))
    56103
    57104def _is_valid_dir_name(s):
    58105    return bool(re.search(r'^\w+$', s))
     
    87134                data_type = f.get_internal_type()
    88135            col_type = db.DATA_TYPES[data_type]
    89136            if col_type is not None:
    90                 field_output = [db.db.quote_name(f.column), col_type % rel_field.__dict__]
    91                 field_output.append('%sNULL' % (not f.null and 'NOT ' or ''))
     137                field_output = [style.SQL_FIELD(db.db.quote_name(f.column)),
     138                                col_type % rel_field.__dict__]
     139                field_output.append(style.SQL_KEYWORD('%sNULL') % \
     140                        (not f.null and 'NOT ' or ''))
    92141                if f.unique:
    93                     field_output.append('UNIQUE')
     142                    field_output.append(style.SQL_KEYWORD('UNIQUE'))
    94143                if f.primary_key:
    95                     field_output.append('PRIMARY KEY')
     144                    field_output.append(style.SQL_KEYWORD('PRIMARY KEY'))
    96145                if f.rel:
    97                     field_output.append('REFERENCES %s (%s)' % \
    98                         (db.db.quote_name(f.rel.to.db_table),
    99                         db.db.quote_name(f.rel.to.get_field(f.rel.field_name).column)))
     146                    field_output.append(J(style.SQL_KEYWORD('REFERENCES'),
     147                                        ' %s (%s)') % \
     148                        (style.SQL_TABLE(db.db.quote_name(f.rel.to.db_table)),
     149                        style.SQL_FIELD(db.db.quote_name(f.rel.to.get_field(f.rel.field_name).column))))
    100150                table_output.append(' '.join(field_output))
    101151        if opts.order_with_respect_to:
    102             table_output.append('%s %s NULL' % (db.db.quote_name('_order'), db.DATA_TYPES['IntegerField']))
     152            table_output.append(J('%s %s ',style.SQL_KEYWORD('NULL')) % \
     153                    (style.SQL_FIELD(db.db.quote_name('_order')),
     154                        db.DATA_TYPES['IntegerField']))
    103155        for field_constraints in opts.unique_together:
    104             table_output.append('UNIQUE (%s)' % \
    105                 ", ".join([db.db.quote_name(opts.get_field(f).column) for f in field_constraints]))
     156            table_output.append(style.SQL_KEYWORD('UNIQUE')+' (%s)' % \
     157                ", ".join([style.SQL_FIELD(db.db.quote_name(opts.get_field(f).column)) for f in field_constraints]))
    106158
    107         full_statement = ['CREATE TABLE %s (' % db.db.quote_name(opts.db_table)]
     159        full_statement = [style.SQL_KEYWORD('CREATE TABLE')+' %s (' % style.SQL_TABLE(db.db.quote_name(opts.db_table))]
    108160        for i, line in enumerate(table_output): # Combine and add commas.
    109161            full_statement.append('    %s%s' % (line, i < len(table_output)-1 and ',' or ''))
    110162        full_statement.append(');')
     
    113165    for klass in mod._MODELS:
    114166        opts = klass._meta
    115167        for f in opts.many_to_many:
    116             table_output = ['CREATE TABLE %s (' % db.db.quote_name(f.get_m2m_db_table(opts))]
    117             table_output.append('    %s %s NOT NULL PRIMARY KEY,' % (db.db.quote_name('id'), db.DATA_TYPES['AutoField']))
    118             table_output.append('    %s %s NOT NULL REFERENCES %s (%s),' % \
    119                 (db.db.quote_name(opts.object_name.lower() + '_id'),
     168            table_output = [J(style.SQL_KEYWORD('CREATE TABLE'),' %s (') % \
     169                    style.SQL_TABLE(db.db.quote_name(f.get_m2m_db_table(opts))
     170                            )]
     171            table_output.append(J('    %s %s ',
     172                style.SQL_KEYWORD('NOT NULL PRIMARY KEY'),',') % \
     173                        (style.SQL_FIELD(db.db.quote_name('id')),
     174                            db.DATA_TYPES['AutoField']))
     175            table_output.append(J('    %s %s ',
     176                style.SQL_KEYWORD('NOT NULL REFERENCES'),' %s (%s),') % \
     177                (style.SQL_FIELD(db.db.quote_name(opts.object_name.lower() + '_id')),
    120178                db.DATA_TYPES[get_rel_data_type(opts.pk)] % opts.pk.__dict__,
    121                 db.db.quote_name(opts.db_table),
    122                 db.db.quote_name(opts.pk.column)))
    123             table_output.append('    %s %s NOT NULL REFERENCES %s (%s),' % \
    124                 (db.db.quote_name(f.rel.to.object_name.lower() + '_id'),
     179                style.SQL_TABLE(db.db.quote_name(opts.db_table)),
     180                style.SQL_FIELD(db.db.quote_name(opts.pk.column))))
     181            table_output.append(J('    %s %s ',
     182                style.SQL_KEYWORD('NOT NULL REFERENCES'),' %s (%s),') % \
     183                (style.SQL_FIELD(db.db.quote_name(f.rel.to.object_name.lower() + '_id')),
    125184                db.DATA_TYPES[get_rel_data_type(f.rel.to.pk)] % f.rel.to.pk.__dict__,
    126                 db.db.quote_name(f.rel.to.db_table),
    127                 db.db.quote_name(f.rel.to.pk.column)))
    128             table_output.append('    UNIQUE (%s, %s)' % \
    129                 (db.db.quote_name(opts.object_name.lower() + '_id'),
    130                 db.db.quote_name(f.rel.to.object_name.lower() + '_id')))
     185                style.SQL_TABLE(db.db.quote_name(f.rel.to.db_table)),
     186                style.SQL_FIELD(db.db.quote_name(f.rel.to.pk.column))))
     187            table_output.append(J('    ',style.SQL_KEYWORD('UNIQUE'),
     188                ' (%s, %s)') % \
     189                (style.SQL_FIELD(db.db.quote_name(opts.object_name.lower() + '_id')),
     190                style.SQL_FIELD(db.db.quote_name(f.rel.to.object_name.lower() + '_id'))))
    131191            table_output.append(');')
    132192            final_output.append('\n'.join(table_output))
    133193    return final_output
     
    167227            # The table doesn't exist, so it doesn't need to be dropped.
    168228            db.db.rollback()
    169229        else:
    170             output.append("DROP TABLE %s;" % db.db.quote_name(klass._meta.db_table))
     230            output.append(J(style.SQL_KEYWORD("DROP TABLE")," %s;") % \
     231                    style.SQL_TABLE(db.db.quote_name(klass._meta.db_table)))
    171232
    172233    # Output DROP TABLE statements for many-to-many tables.
    173234    for klass in mod._MODELS:
     
    175236        for f in opts.many_to_many:
    176237            try:
    177238                if cursor is not None:
    178                     cursor.execute("SELECT 1 FROM %s LIMIT 1" % db.db.quote_name(f.get_m2m_db_table(opts)))
     239                    cursor.execute("SELECT 1 FROM %s LIMIT 1" % \
     240                            db.db.quote_name(f.get_m2m_db_table(opts)))
    179241            except:
    180242                db.db.rollback()
    181243            else:
    182                 output.append("DROP TABLE %s;" % db.db.quote_name(f.get_m2m_db_table(opts)))
     244                output.append(J(style.SQL_KEYWORD("DROP TABLE")," %s;") % \
     245                        style.SQL_TABLE(db.db.quote_name(f.get_m2m_db_table(opts))))
    183246
    184247    app_label = mod._MODELS[0]._meta.app_label
    185248
    186249    # Delete from packages, auth_permissions, content_types.
    187     output.append("DELETE FROM %s WHERE %s = '%s';" % \
    188         (db.db.quote_name('packages'), db.db.quote_name('label'), app_label))
    189     output.append("DELETE FROM %s WHERE %s = '%s';" % \
    190         (db.db.quote_name('auth_permissions'), db.db.quote_name('package'), app_label))
    191     output.append("DELETE FROM %s WHERE %s = '%s';" % \
    192         (db.db.quote_name('content_types'), db.db.quote_name('package'), app_label))
     250    output.append(J(style.SQL_KEYWORD("DELETE FROM")," %s ",
     251        style.SQL_KEYWORD("WHERE")," %s = %s;") % \
     252        (style.SQL_TABLE(db.db.quote_name('packages')),
     253            style.SQL_FIELD(db.db.quote_name('label')),
     254            style.SQL_STRING("'"+app_label+"'")))
     255    output.append(J(style.SQL_KEYWORD("DELETE FROM")," %s ",
     256        style.SQL_KEYWORD("WHERE")," %s = %s;") % \
     257        (style.SQL_TABLE(db.db.quote_name('auth_permissions')),
     258            style.SQL_FIELD(db.db.quote_name('package')),
     259            style.SQL_STRING("'"+app_label+"'")))
     260    output.append(J(style.SQL_KEYWORD("DELETE FROM")," %s ",
     261        style.SQL_KEYWORD("WHERE")," %s = %s;") % \
     262        (style.SQL_TABLE(db.db.quote_name('content_types')),
     263            style.SQL_FIELD(db.db.quote_name('package')),
     264            style.SQL_STRING("'"+app_label+"'")))
    193265
    194266    # Delete from the admin log.
    195267    if cursor is not None:
     
    198270            db.db.quote_name('package')), [app_label])
    199271        if admin_log_exists:
    200272            for row in cursor.fetchall():
    201                 output.append("DELETE FROM %s WHERE %s = %s;" % \
    202                     (db.db.quote_name('django_admin_log'), db.db.quote_name('content_type_id'), row[0]))
     273                output.append(J(style.SQL_KEYWORD("DELETE FROM")," %s ",
     274                    style.SQL_KEYWORD("WHERE")," %s = %s;") % \
     275                    (style.SQL_TABLE(db.db.quote_name('django_admin_log')),
     276                        style.SQL_FIELD(db.db.quote_name('content_type_id')),
     277                        style.SQL_NUMBER(row[0])))
    203278
    204279    # Close database connection explicitly, in case this output is being piped
    205280    # directly into a database client, to avoid locking issues.
     
    252327    for klass in mod._MODELS:
    253328        for f in klass._meta.fields:
    254329            if isinstance(f, meta.AutoField):
    255                 output.append("SELECT setval('%s_%s_seq', (SELECT max(%s) FROM %s));" % \
    256                     (klass._meta.db_table, f.column, db.db.quote_name(f.column),
    257                     db.db.quote_name(klass._meta.db_table)))
     330                output.append(J(style.SQL_KEYWORD("SELECT"),
     331                    " setval('%s_%s_seq', (",
     332                    style.SQL_KEYWORD("SELECT")," max(%s) ",
     333                    style.SQL_KEYWORD("FROM")," %s));") % \
     334                    (klass._meta.db_table,
     335                        f.column,
     336                        style.SQL_FIELD(db.db.quote_name(f.column)),
     337                    style.SQL_TABLE(db.db.quote_name(klass._meta.db_table))))
    258338        for f in klass._meta.many_to_many:
    259             output.append("SELECT setval('%s_id_seq', (SELECT max(%s) FROM %s));" % \
    260                 (f.get_m2m_db_table(klass._meta), db.db.quote_name('id'), f.get_m2m_db_table(klass._meta)))
     339            output.append(J(style.SQL_KEYWORD("SELECT"),
     340                " setval('%s_id_seq', (",
     341                style.SQL_KEYWORD("SELECT")," max(%s) ",
     342                style.SQL_KEYWORD("FROM")," %s));") % \
     343                (f.get_m2m_db_table(klass._meta),
     344                    style.SQL_FIELD(db.db.quote_name('id')),
     345                    style.SQL_TABLE(f.get_m2m_db_table(klass._meta))))
    261346    return output
    262347get_sql_sequence_reset.help_doc = "Prints the SQL statements for resetting PostgreSQL sequences for the given model module name(s)."
    263348get_sql_sequence_reset.args = APP_ARGS
     
    270355        for f in klass._meta.fields:
    271356            if f.db_index:
    272357                unique = f.unique and "UNIQUE " or ""
    273                 output.append("CREATE %sINDEX %s_%s ON %s (%s);" % \
     358                output.append(J(style.SQL_KEYWORD("CREATE %sINDEX")," %s_%s ",style.SQL_KEYWORD("ON")," %s (%s);") % \
    274359                    (unique, klass._meta.db_table, f.column,
    275                     db.quote_name(klass._meta.db_table), db.quote_name(f.column)))
     360                    style.SQL_TABLE(db.quote_name(klass._meta.db_table)),
     361                    style.SQL_FIELD(db.quote_name(f.column))))
    276362    return output
    277363get_sql_indexes.help_doc = "Prints the CREATE INDEX SQL statements for the given model module name(s)."
    278364get_sql_indexes.args = APP_ARGS
     
    337423            perms_seen[row[0]]
    338424        except KeyError:
    339425#             sys.stderr.write("A permission called '%s.%s' was found in the database but not in the model.\n" % (app_label, row[0]))
    340             print "DELETE FROM %s WHERE %s='%s' AND %s = '%s';" % \
    341                 (db.db.quote_name('auth_permissions'), db.db.quote_name('package'),
    342                 app_label, db.db.quote_name('codename'), row[0])
     426            print J(style.SQL_KEYWORD("DELETE FROM"), " %s ",
     427                    style.SQL_KEYWORD("WHERE"), " %s='%s' ",
     428                    style.SQL_KEYWORD("AND"), " %s = '%s';") % \
     429                (style.SQL_TABLE(db.db.quote_name('auth_permissions')),
     430                        style.SQL_FIELD(db.db.quote_name('package')),
     431                        style.SQL_STRING(app_label),
     432                        style.SQL_FIELD(db.db.quote_name('codename')),
     433                        style.SQL_STRING(row[0]))
    343434
    344435    # Check that there aren't any *extra* content types in the DB that the
    345436    # model doesn't know about.
     
    351442            contenttypes_seen[row[0]]
    352443        except KeyError:
    353444#             sys.stderr.write("A content type called '%s.%s' was found in the database but not in the model.\n" % (app_label, row[0]))
    354             print "DELETE FROM %s WHERE %s='%s' AND %s = '%s';" % \
    355                 (db.db.quote_name('content_types'), db.db.quote_name('package'),
    356                 app_label, db.db.quote_name('python_module_name'), row[0])
     445            print J(style.SQL_KEYWORD("DELETE FROM")," %s ",
     446                    style.SQL_KEYWORD("WHERE")," %s='%s' ",
     447                    style.SQL_KEYWORD("AND")," %s = '%s';") % \
     448                (style.SQL_TABLE(db.db.quote_name('content_types')),
     449                        style.SQL_FIELD(db.db.quote_name('package')),
     450                        style.SQL_STRING(app_label),
     451                        style.SQL_FIELD(db.db.quote_name('python_module_name')),
     452                        style.SQL_STRING(row[0]))
    357453database_check.help_doc = "Checks that everything is installed in the database for the given model module name(s) and prints SQL statements if needed."
    358454database_check.args = APP_ARGS
    359455
     
    381477
    382478def init():
    383479    "Initializes the database with auth and core."
     480    disable_sql_styles()
    384481    try:
    385482        from django.core import db, meta
    386483        auth = meta.get_app('auth')
     
    392489            (db.db.quote_name(core.Site._meta.db_table), db.db.quote_name('domain'),
    393490            db.db.quote_name('name')))
    394491    except Exception, e:
    395         sys.stderr.write("Error: The database couldn't be initialized.\n%s\n" % e)
     492        sys.stderr.write(
     493                J(style.ERROR("Error: The database couldn't be initialized."),
     494                    "\n",style.ERROR_OUTPUT(e),"\n")
     495                    )
    396496        try:
    397497            db.db.rollback()
    398498        except UnboundLocalError:
     
    408508    from cStringIO import StringIO
    409509    mod_name = mod.__name__[mod.__name__.rindex('.')+1:]
    410510
     511    disable_sql_styles()
    411512    # First, try validating the models.
    412513    s = StringIO()
    413514    num_errors = get_validation_errors(s)
    414515    if num_errors:
    415         sys.stderr.write("Error: %s couldn't be installed, because there were errors in your model:\n" % mod_name)
     516        sys.stderr.write(J(style.ERROR("Error: %s couldn't be installed, because there were errors in your model:"),"\n") % mod_name)
    416517        s.seek(0)
    417         sys.stderr.write(s.read())
     518        sys.stderr.write(style.ERROR_OUTPUT(s.read()))
    418519        sys.exit(1)
    419520    sql_list = get_sql_all(mod)
    420521
     
    423524        for sql in sql_list:
    424525            cursor.execute(sql)
    425526    except Exception, e:
    426         sys.stderr.write("""Error: %s couldn't be installed. Possible reasons:
     527        sys.stderr.write(
     528        J(style.ERROR("Error: %s couldn't be installed. Possible reasons:"),
     529        style.ERROR_OUTPUT("""
    427530  * The database isn't running or isn't configured correctly.
    428531  * At least one of the database tables already exists.
    429532  * The SQL was invalid.
    430533Hint: Look at the output of 'django-admin.py sqlall %s'. That's the SQL this command wasn't able to run.
    431 The full error: %s\n""" % \
     534The full error: %s"""),"\n") % \
    432535            (mod_name, mod_name, e))
    433536        db.db.rollback()
    434537        sys.exit(1)
     
    440543    "Installs any permissions for the given model, if needed."
    441544    from django.models.auth import permissions
    442545    from django.models.core import packages
     546
     547    disable_sql_styles()
     548   
    443549    num_added = 0
    444550    package = packages.get_object(pk=mod._MODELS[0]._meta.app_label)
    445551    for klass in mod._MODELS:
     
    450556            except permissions.PermissionDoesNotExist:
    451557                p = permissions.Permission(name=name, package=package, codename=codename)
    452558                p.save()
    453                 print "Added permission '%r'." % p
     559                print style.OK("Added permission '%r'." % p)
    454560                num_added += 1
    455561    if not num_added:
    456         print "No permissions were added, because all necessary permissions were already installed."
     562        print style.OK("No permissions were added, because all necessary permissions were already installed.")
    457563installperms.help_doc = "Installs any permissions for the given model module name(s), if needed."
    458564installperms.args = APP_ARGS
    459565
    460566def _start_helper(app_or_project, name, directory, other_name=''):
    461567    other = {'project': 'app', 'app': 'project'}[app_or_project]
    462568    if not _is_valid_dir_name(name):
    463         sys.stderr.write("Error: %r is not a valid %s name. Please use only numbers, letters and underscores.\n" % (name, app_or_project))
     569        sys.stderr.write(J(style.ERROR("Error: %r is not a valid %s name. Please use only numbers, letters and underscores."),"\n") % (name, app_or_project))
    464570        sys.exit(1)
    465571    top_dir = os.path.join(directory, name)
    466572    try:
    467573        os.mkdir(top_dir)
    468574    except OSError, e:
    469         sys.stderr.write("Error: %s\n" % e)
     575        sys.stderr.write(J(style.ERROR("Error: %s"),"\n") % e)
    470576        sys.exit(1)
    471577    template_dir = PROJECT_TEMPLATE_DIR % app_or_project
    472578    for d, subdirs, files in os.walk(template_dir):
     
    489595    "Creates a Django project for the given project_name in the given directory."
    490596    from random import choice
    491597    if project_name in INVALID_PROJECT_NAMES:
    492         sys.stderr.write("Error: %r isn't a valid project name. Please try another.\n" % project_name)
     598        sys.stderr.write(J(style.ERROR("Error: %r isn't a valid project name. Please try another."),"\n") % project_name)
    493599        sys.exit(1)
    494600    _start_helper('project', project_name, directory)
    495601    # Create a random SECRET_KEY hash, and put it in the main settings.
    496602    main_settings_file = os.path.join(directory, project_name, 'settings.py')
    497603    settings_contents = open(main_settings_file, 'r').read()
    498604    fp = open(main_settings_file, 'w')
    499     secret_key = ''.join([choice('abcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*(-_=+)') for i in range(50)])
     605    secret_key = J([choice('abcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*(-_=+)') for i in range(50)])
    500606    settings_contents = re.sub(r"(?<=SECRET_KEY = ')'", secret_key + "'", settings_contents)
    501607    fp.write(settings_contents)
    502608    fp.close()
     
    523629            if not username:
    524630                username = raw_input('Username (only letters, digits and underscores): ')
    525631            if not username.isalnum():
    526                 sys.stderr.write("Error: That username is invalid.\n")
     632                sys.stderr.write(J(style.ERROR("Error: That username is invalid."),"\n"))
    527633                username = None
    528634            try:
    529635                users.get_object(username__exact=username)
    530636            except users.UserDoesNotExist:
    531637                break
    532638            else:
    533                 sys.stderr.write("Error: That username is already taken.\n")
     639                sys.stderr.write(J(style.ERROR("Error: That username is already taken."),"\n"))
    534640                username = None
    535641        while 1:
    536642            if not email:
     
    538644            try:
    539645                validators.isValidEmail(email, None)
    540646            except validators.ValidationError:
    541                 sys.stderr.write("Error: That e-mail address is invalid.\n")
     647                sys.stderr.write(J(style.ERROR("Error: That e-mail address is invalid."),"\n"))
    542648                email = None
    543649            else:
    544650                break
     
    547653                password = getpass.getpass()
    548654                password2 = getpass.getpass('Password (again): ')
    549655                if password != password2:
    550                     sys.stderr.write("Error: Your passwords didn't match.\n")
     656                    sys.stderr.write(J(style.ERROR("Error: Your passwords didn't match."),"\n"))
    551657                    password = None
    552658                    continue
    553659            if password.strip() == '':
    554                 sys.stderr.write("Error: Blank passwords aren't allowed.\n")
     660                sys.stderr.write(J(style.ERROR("Error: Blank passwords aren't allowed."),"\n"))
    555661                password = None
    556662                continue
    557663            break
    558664    except KeyboardInterrupt:
    559         sys.stderr.write("\nOperation cancelled.\n")
     665        sys.stderr.write(J('\n',style.ERROR("Operation cancelled."),'\n'))
    560666        sys.exit(1)
    561667    u = users.create_user(username, email, password)
    562668    u.is_staff = True
    563669    u.is_active = True
    564670    u.is_superuser = True
    565671    u.save()
    566     print "User created successfully."
     672    print style.OK("User created successfully.")
    567673createsuperuser.args = '[username] [email] [password] (Either all or none)'
    568674
    569675def inspectdb(db_name):
     
    798904    if not addr:
    799905        addr = '127.0.0.1'
    800906    if not port.isdigit():
    801         sys.stderr.write("Error: %r is not a valid port number.\n" % port)
     907        sys.stderr.write(style.ERROR("Error: %r is not a valid port number.\n" % port))
    802908        sys.exit(1)
    803909    def inner_run():
    804910        from django.conf.settings import SETTINGS_MODULE
    805911        print "Validating models..."
    806912        validate()
    807         print "\nDjango version %s, using settings %r" % (get_version(), SETTINGS_MODULE)
    808         print "Development server is running at http://%s:%s/" % (addr, port)
     913        print
     914        print style.OK("Django version %s, using settings %r") % (get_version(), SETTINGS_MODULE)
     915        print style.OK("Development server is running at http://%s:%s/" % (addr, port))
    809916        print "Quit the server with CONTROL-C (Unix) or CTRL-BREAK (Windows)."
    810917        try:
    811918            run(addr, int(port), AdminMediaHandler(WSGIHandler()))
     
    820927                error_text = ERRORS[e.args[0].args[0]]
    821928            except (AttributeError, KeyError):
    822929                error_text = str(e)
    823             sys.stderr.write("Error: %s\n" % error_text)
     930            sys.stderr.write(style.ERROR("Error: %s\n" % error_text))
    824931            sys.exit(1)
    825932        except KeyboardInterrupt:
    826933            sys.exit(0)
     
    9251032    return '\n'.join(usage[:-1]) # Cut off last list element, an empty space.
    9261033
    9271034def print_error(msg, cmd):
    928     sys.stderr.write('Error: %s\nRun "%s --help" for help.\n' % (msg, cmd))
     1035    sys.stderr.write(J(style.ERROR('Error: %s'),'\n',style.ERROR_OUTPUT('Run "%s --help" for help.'),'\n') % (msg, cmd))
    9291036    sys.exit(1)
    9301037
    9311038def execute_from_command_line(action_mapping=DEFAULT_ACTION_MAPPING):
     
    9681075            if len(args) == 1: # We got no arguments, just the action.
    9691076                action_mapping[action]()
    9701077            else:
    971                 sys.stderr.write("Error: %r requires arguments of 'username email password' or no argument at all.\n")
     1078                sys.stderr.write(J(style.ERROR("Error: %r requires arguments of 'username email password' or no argument at all."),"\n"))
    9721079                sys.exit(1)
    9731080        else:
    9741081            action_mapping[action](username, email, password)
     
    9851092            for line in action_mapping[action](param):
    9861093                print line
    9871094        except NotImplementedError:
    988             sys.stderr.write("Error: %r isn't supported for the currently selected database backend.\n" % action)
     1095            sys.stderr.write(J(style.ERROR("Error: %r isn't supported for the currently selected database backend."),"\n") % action)
    9891096            sys.exit(1)
    9901097    elif action == 'createcachetable':
    9911098        try:
     
    10161123            try:
    10171124                mod_list = [meta.get_app(app_label) for app_label in args[1:]]
    10181125            except ImportError, e:
    1019                 sys.stderr.write("Error: %s. Are you sure your INSTALLED_APPS setting is correct?\n" % e)
     1126                sys.stderr.write(J(style.ERROR("Error: %s. Are you sure your INSTALLED_APPS setting is correct?"),"\n") % e)
    10201127                sys.exit(1)
    10211128            if not mod_list:
    10221129                parser.print_usage_and_exit()
    10231130        if action not in NO_SQL_TRANSACTION:
    1024             print "BEGIN;"
     1131            print J(style.SQL_TRANS("BEGIN"), ';')
    10251132        for mod in mod_list:
    10261133            output = action_mapping[action](mod)
    10271134            if output:
    10281135                print '\n'.join(output)
    10291136        if action not in NO_SQL_TRANSACTION:
    1030             print "COMMIT;"
     1137            print J(style.SQL_TRANS("COMMIT"),';')
    10311138
    10321139def execute_manager(settings_mod):
    10331140    # Add this project to sys.path so that it's importable in the conventional
Back to Top