app/django/core/management/commands/startproject.py
changeset 54 03e267d67478
child 323 ff1a9aa48cfd
equal deleted inserted replaced
53:57b4279d8c4e 54:03e267d67478
       
     1 from django.core.management.base import copy_helper, CommandError, LabelCommand
       
     2 import os
       
     3 import re
       
     4 from random import choice
       
     5 
       
     6 INVALID_PROJECT_NAMES = ('django', 'site', 'test')
       
     7 
       
     8 class Command(LabelCommand):
       
     9     help = "Creates a Django project directory structure for the given project name in the current directory."
       
    10     args = "[projectname]"
       
    11     label = 'project name'
       
    12 
       
    13     requires_model_validation = False
       
    14     # Can't import settings during this command, because they haven't
       
    15     # necessarily been created.
       
    16     can_import_settings = False
       
    17 
       
    18     def handle_label(self, project_name, **options):
       
    19         # Determine the project_name a bit naively -- by looking at the name of
       
    20         # the parent directory.
       
    21         directory = os.getcwd()
       
    22 
       
    23         try:
       
    24             proj_name = __import__(project_name)
       
    25             if proj_name:
       
    26                 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)
       
    27         except ImportError:
       
    28             if project_name in INVALID_PROJECT_NAMES:
       
    29                 raise CommandError("%r contains an invalid project name. Please try another name." % project_name)
       
    30 
       
    31         copy_helper(self.style, 'project', project_name, directory)
       
    32 
       
    33         # Create a random SECRET_KEY hash, and put it in the main settings.
       
    34         main_settings_file = os.path.join(directory, project_name, 'settings.py')
       
    35         settings_contents = open(main_settings_file, 'r').read()
       
    36         fp = open(main_settings_file, 'w')
       
    37         secret_key = ''.join([choice('abcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*(-_=+)') for i in range(50)])
       
    38         settings_contents = re.sub(r"(?<=SECRET_KEY = ')'", secret_key + "'", settings_contents)
       
    39         fp.write(settings_contents)
       
    40         fp.close()