Django

Code

Changeset 2551

Show
Ignore:
Timestamp:
03/22/06 18:55:30 (3 years ago)
Author:
adrian
Message:

magic-removal: Removed app-specific stuff from django.core.management.syncdb, in favor of an event-based system. Permissions, superusers and the example.com site are now all done via a management.py file within the appropriate contrib app. This also means 'createsuperuser' is no longer a django-admin command...We'll probably want to restore that somehow, or add another utility that does it from the command line.

Files:

Legend:

Unmodified
Added
Removed
Modified
Copied
Moved
  • django/branches/magic-removal/django/core/management.py

    r2541 r2551  
    2626 
    2727INVALID_PROJECT_NAMES = ('django', 'test') 
    28  
    29 def _get_permission_codename(action, opts): 
    30     return '%s_%s' % (action, opts.object_name.lower()) 
    31  
    32 def _get_all_permissions(opts): 
    33     "Returns (codename, name) for all permissions in the given opts." 
    34     perms = [] 
    35     if opts.admin: 
    36         for action in ('add', 'change', 'delete'): 
    37             perms.append((_get_permission_codename(action, opts), 'Can %s %s' % (action, opts.verbose_name))) 
    38     return perms + list(opts.permissions) 
    39  
    40 def _get_permission_insert(name, codename, opts): 
    41     from django.db import backend 
    42     return "INSERT INTO %s (%s, %s, %s) VALUES ('%s', '%s', '%s');" % \ 
    43         (backend.quote_name('auth_permission'), backend.quote_name('name'), backend.quote_name('package'), 
    44         backend.quote_name('codename'), name.replace("'", "''"), opts.app_label, codename) 
    4528 
    4629def _is_valid_dir_name(s): 
     
    399382    "Creates the database tables for all apps in INSTALLED_APPS whose tables haven't already been created." 
    400383    from django.db import connection, transaction, models, get_creation_module 
     384    from django.db.models import signals 
     385    from django.conf import settings 
     386    from django.dispatch import dispatcher 
    401387 
    402388    # Check that there are no validation errors before continuing 
    403389    _check_for_validation_errors() 
     390 
     391    # Import the 'management' module within each installed app, to register 
     392    # dispatcher events. 
     393    for app_name in settings.INSTALLED_APPS: 
     394        try: 
     395            __import__(app_name + '.management', '', '', ['']) 
     396        except ImportError: 
     397            pass 
    404398 
    405399    data_types = get_creation_module().DATA_TYPES 
     
    415409    created_models = set() 
    416410    pending_references = {} 
    417     install_permissions = True 
    418411 
    419412    for app in models.get_apps(): 
     
    442435        transaction.commit_unless_managed() 
    443436 
    444     # Install permissions and initial data (first checking that they're installed) 
     437    # Send the post_syncdb signal, so individual apps can do whatever they need 
     438    # to do at this point. 
    445439    for app in models.get_apps(): 
    446         if install_permissions: 
    447             try: 
    448                 installperms(app) 
    449             except Exception, e: 
    450                 # stop trying to install permissions 
    451                 install_permissions = False 
    452                 sys.stderr.write("Permissions will not be installed because it "\ 
    453                                  "appears that you are not using Django's auth framework. "\ 
    454                                  "If you want to install them in the future, re-run syncdb."\ 
    455                                  "\n(The full error was: %s)\n" % e) 
    456                 transaction.rollback_unless_managed() 
    457             else: 
    458                 transaction.commit_unless_managed() 
     440        dispatcher.send(signal=signals.post_syncdb, sender=app, 
     441            app=app, created_models=created_models) 
    459442 
    460443        # Install initial data for the app (but only if this is a model we've 
     
    474457                    else: 
    475458                        transaction.commit_unless_managed() 
    476  
    477     # Create an initial "example.com" site (if we need to) 
    478     from django.contrib.sites.models import Site 
    479     if Site in created_models: 
    480         print "Creating example site object" 
    481         ex = Site(domain="example.com", name="example.com") 
    482         ex.save() 
    483  
    484     # If we just installed the User model, ask about creating a superuser 
    485     from django.contrib.auth.models import User 
    486     if User in created_models: 
    487         msg = "\nYou just installed Django's auth system, which means you don't have " \ 
    488               "any superusers defined.\nWould you like to create one now? (yes/no): " 
    489         confirm = raw_input(msg) 
    490         while 1: 
    491             if confirm not in ('yes', 'no'): 
    492                 confirm = raw_input('Please enter either "yes" or "no": ') 
    493                 continue 
    494             if confirm == 'yes': 
    495                 createsuperuser() 
    496             break 
    497459 
    498460syncdb.args = '' 
     
    585547reset.help_doc = "Executes ``sqlreset`` for the given app(s) in the current database." 
    586548reset.args = APP_ARGS 
    587  
    588 def installperms(app): 
    589     "Installs any permissions for the given app, if needed." 
    590     from django.contrib.contenttypes.models import ContentType 
    591     from django.contrib.auth.models import Permission 
    592     from django.db.models import get_models 
    593     app_models = get_models(app) 
    594     if not app_models: 
    595         return 
    596     app_label = app_models[0]._meta.app_label 
    597     num_added = 0 
    598     for klass in app_models: 
    599         opts = klass._meta 
    600         ctype = ContentType.objects.get_for_model(klass) 
    601         for codename, name in _get_all_permissions(opts): 
    602             try: 
    603                 Permission.objects.get(name=name, codename=codename, content_type__pk=ctype.id) 
    604             except Permission.DoesNotExist: 
    605                 p = Permission(name=name, codename=codename, content_type=ctype) 
    606                 p.save() 
    607                 print "Adding permission '%r'." % p 
    608                 num_added += 1 
    609 installperms.help_doc = "Installs any permissions for the given model module name(s), if needed." 
    610 installperms.args = APP_ARGS 
    611549 
    612550def _start_helper(app_or_project, name, directory, other_name=''): 
     
    665603startapp.help_doc = "Creates a Django app directory structure for the given app name in the current directory." 
    666604startapp.args = "[appname]" 
    667  
    668 def createsuperuser(username=None, email=None, password=None): 
    669     "Creates a superuser account." 
    670     from django.core import validators 
    671     from django.contrib.auth.models import User 
    672     import getpass 
    673  
    674     try: 
    675         import pwd 
    676     except ImportError: 
    677         default_username = '' 
    678     else: 
    679         # Determine the current system user's username, to use as a default. 
    680         default_username = pwd.getpwuid(os.getuid())[0].replace(' ', '').lower() 
    681  
    682     # Determine whether the default username is taken, so we don't display 
    683     # it as an option. 
    684     if default_username: 
    685         try: 
    686             User.objects.get(username=default_username) 
    687         except User.DoesNotExist: 
    688             pass 
    689         else: 
    690             default_username = '' 
    691  
    692     try: 
    693         while 1: 
    694             if not username: 
    695                 input_msg = 'Username' 
    696                 if default_username: 
    697                     input_msg += ' (Leave blank to use %r)' % default_username 
    698                 username = raw_input(input_msg + ': ') 
    699             if default_username and username == '': 
    700                 username = default_username 
    701             if not username.isalnum(): 
    702                 sys.stderr.write("Error: That username is invalid. Use only letters, digits and underscores.\n") 
    703                 username = None 
    704             try: 
    705                 User.objects.get(username=username) 
    706             except User.DoesNotExist: 
    707                 break 
    708             else: 
    709                 sys.stderr.write("Error: That username is already taken.\n") 
    710                 username = None 
    711         while 1: 
    712             if not email: 
    713                 email = raw_input('E-mail address: ') 
    714             try: 
    715                 validators.isValidEmail(email, None) 
    716             except validators.ValidationError: 
    717                 sys.stderr.write("Error: That e-mail address is invalid.\n") 
    718                 email = None 
    719             else: 
    720                 break 
    721         while 1: 
    722             if not password: 
    723                 password = getpass.getpass() 
    724                 password2 = getpass.getpass('Password (again): ') 
    725                 if password != password2: 
    726                     sys.stderr.write("Error: Your passwords didn't match.\n") 
    727                     password = None 
    728                     continue 
    729             if password.strip() == '': 
    730                 sys.stderr.write("Error: Blank passwords aren't allowed.\n") 
    731                 password = None 
    732                 continue 
    733             break 
    734     except KeyboardInterrupt: 
    735         sys.stderr.write("\nOperation cancelled.\n") 
    736         sys.exit(1) 
    737     u = User.objects.create_user(username, email, password) 
    738     u.is_staff = True 
    739     u.is_active = True 
    740     u.is_superuser = True 
    741     u.save() 
    742     print "User created successfully." 
    743 createsuperuser.args = '[username] [email] [password] (Either all or none)' 
    744605 
    745606def inspectdb(db_name): 
     
    1121982DEFAULT_ACTION_MAPPING = { 
    1122983    'adminindex': get_admin_index, 
    1123     'createsuperuser': createsuperuser, 
    1124984    'createcachetable' : createcachetable, 
    1125985    'inspectdb': inspectdb, 
    1126986    'install': install, 
    1127     'installperms': installperms, 
    1128987    'reset': reset, 
    1129988    'runserver': runserver, 
     
    11461005    'createcachetable', 
    11471006    'install', 
    1148     'installperms', 
    11491007    'reset', 
    11501008    'sqlindexes' 
     
    12081066        translation.activate('en-us') 
    12091067 
    1210     if action == 'createsuperuser': 
    1211         try: 
    1212             username, email, password = args[1], args[2], args[3] 
    1213         except IndexError: 
    1214             if len(args) == 1: # We got no arguments, just the action. 
    1215                 action_mapping[action]() 
    1216             else: 
    1217                 sys.stderr.write("Error: %r requires arguments of 'username email password' or no argument at all.\n") 
    1218                 sys.exit(1) 
    1219         else: 
    1220             action_mapping[action](username, email, password) 
    1221     elif action == 'shell': 
     1068    if action == 'shell': 
    12221069        action_mapping[action](options.plain is True) 
    12231070    elif action in ('syncdb', 'validate'): 
  • django/branches/magic-removal/django/db/models/signals.py

    r1721 r2551  
    99pre_delete = object() 
    1010post_delete = object() 
     11 
     12post_syncdb = object() 
  • django/branches/magic-removal/docs/django-admin.txt

    r2351 r2551  
    6464 
    6565.. _cache documentation: http://www.djangoproject.com/documentation/cache/ 
    66  
    67 createsuperuser 
    68 --------------- 
    69  
    70 Creates a superuser account interactively. It asks you for a username, e-mail 
    71 address and password. 
    72  
    73 You can specify ``username email password`` on the command line, for convenient 
    74 use in shell scripts. Example:: 
    75  
    76     django-admin.py createsuperuser john john@example.com mypassword 
    77  
    78 init 
    79 ---- 
    80  
    81 Initializes the database with the tables and data Django needs by default. 
    82 Specifically, these are the database tables from the ``auth`` and ``core`` 
    83 models. 
    8466 
    8567inspectdb [dbname] 
     
    129111Executes the equivalent of ``sqlall`` for the given model module(s). 
    130112 
    131 installperms [modelmodule modelmodule ...] 
    132 ------------------------------------------ 
    133  
    134 Installs any admin permissions for the given model module(s) that aren't 
    135 already installed in the database. Outputs a message telling how many 
    136 permissions were added, if any. 
    137  
    138113runserver [optional port number, or ipaddr:port] 
    139114------------------------------------------------