django.utils.six.moves.input

Here are the examples of the python api django.utils.six.moves.input taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

144 Examples 7

Example 1

View license
    def _choice_input(self, question, choices):
        print(question)
        for i, choice in enumerate(choices):
            print(" %s) %s" % (i + 1, choice))
        result = input("Select an option: ")
        while True:
            try:
                value = int(result)
                if 0 < value <= len(choices):
                    return value
            except ValueError:
                pass
            result = input("Please select a valid option: ")

Example 2

Project: GAE-Bulk-Mailer
Source File: creation.py
View license
    def _create_test_db(self, verbosity, autoclobber):
        test_database_name = self._get_test_db_name()
        if test_database_name != ':memory:':
            # Erase the old test database
            if verbosity >= 1:
                print("Destroying old test database '%s'..." % self.connection.alias)
            if os.access(test_database_name, os.F_OK):
                if not autoclobber:
                    confirm = input("Type 'yes' if you would like to try deleting the test database '%s', or 'no' to cancel: " % test_database_name)
                if autoclobber or confirm == 'yes':
                    try:
                        os.remove(test_database_name)
                    except Exception as e:
                        sys.stderr.write("Got an error deleting the old test database: %s\n" % e)
                        sys.exit(2)
                else:
                    print("Tests cancelled.")
                    sys.exit(1)
        return test_database_name

Example 3

Project: treeherder
Source File: init_datasources.py
View license
    def handle(self, *args, **options):
        if options["reset"]:
            confirm = input("""You have requested an init of the datasources.
This will IRREVERSIBLY DESTROY all data in the per-project databases.
Are you sure you want to do this?

Type 'yes' to continue, or 'no' to cancel: """)
            if confirm == "yes":
                for ds in Datasource.objects.all():
                    ds.delete()

        projects = Repository.objects.filter(active_status='active').values_list('name', flat=True)
        for project in projects:
            Datasource.objects.get_or_create(project=project)
        Datasource.reset_cache()

Example 4

Project: PyClassLessons
Source File: creation.py
View license
    def _create_test_db(self, verbosity, autoclobber):
        test_database_name = self._get_test_db_name()
        if test_database_name != ':memory:':
            # Erase the old test database
            if verbosity >= 1:
                print("Destroying old test database '%s'..." % self.connection.alias)
            if os.access(test_database_name, os.F_OK):
                if not autoclobber:
                    confirm = input("Type 'yes' if you would like to try deleting the test database '%s', or 'no' to cancel: " % test_database_name)
                if autoclobber or confirm == 'yes':
                    try:
                        os.remove(test_database_name)
                    except Exception as e:
                        sys.stderr.write("Got an error deleting the old test database: %s\n" % e)
                        sys.exit(2)
                else:
                    print("Tests cancelled.")
                    sys.exit(1)
        return test_database_name

Example 5

Project: decode-Django
Source File: __init__.py
View license
def create_superuser(app, created_models, verbosity, db, **kwargs):
    from django.core.management import call_command

    UserModel = get_user_model()

    if UserModel in created_models and kwargs.get('interactive', True):
        msg = ("\nYou just installed Django's auth system, which means you "
            "don't have any superusers defined.\nWould you like to create one "
            "now? (yes/no): ")
        confirm = input(msg)
        while 1:
            if confirm not in ('yes', 'no'):
                confirm = input('Please enter either "yes" or "no": ')
                continue
            if confirm == 'yes':
                call_command("createsuperuser", interactive=True, database=db)
            break

Example 6

Project: PyClassLessons
Source File: questioner.py
View license
    def _choice_input(self, question, choices):
        print(question)
        for i, choice in enumerate(choices):
            print(" %s) %s" % (i + 1, choice))
        result = input("Select an option: ")
        while True:
            try:
                value = int(result)
                if 0 < value <= len(choices):
                    return value
            except ValueError:
                pass
            result = input("Please select a valid option: ")

Example 7

Project: Spirit
Source File: spirittx.py
View license
    def handle(self, *args, **options):
        # todo: test!
        # Requires "pip install transifex-client==0.11"

        call_command('spirittxpull', stdout=self.stdout, stderr=self.stderr)
        call_command('spiritmakelocales', stdout=self.stdout, stderr=self.stderr)
        message = (
            "Push is destructive, please review "
            "the locale changes, run `$ git diff`\n"
            "Do you want to push the changes? y/n: "
        )

        if input(message).lower() == "y":
            call_command('spirittxpush', stdout=self.stdout, stderr=self.stderr)

        self.stdout.write('ok')

Example 8

View license
def ask_confirmation(app_label, db_name):
    return input("""You have requested a reset of the application {app_label}.
This will IRREVERSIBLY DESTROY all data related to the app currently in
the {db_name} database, and return each table to empty state.
Are you sure you want to do this?
    Type 'yes' to continue, or 'no' to cancel: """.format(**locals()))

Example 9

Project: django
Source File: createsuperuser.py
View license
    def get_input_data(self, field, message, default=None):
        """
        Override this method if you want to customize data inputs or
        validation exceptions.
        """
        raw_value = input(message)
        if default and raw_value == '':
            raw_value = default
        try:
            val = field.clean(raw_value, None)
        except exceptions.ValidationError as e:
            self.stderr.write("Error: %s" % '; '.join(e.messages))
            val = None

        return val

Example 10

Project: django-cms
Source File: uninstall.py
View license
    def handle_label(self, label, **options):
        queryset = Page.objects.filter(application_urls=label)
        number_of_apphooks = queryset.count()

        if number_of_apphooks > 0:
            if options.get('interactive'):
                confirm = input("""
You have requested to remove %d '%s' apphooks.
Are you sure you want to do this?
Type 'yes' to continue, or 'no' to cancel: """ % (number_of_apphooks, label))
            else:
                confirm = 'yes'
            if confirm == 'yes':
                queryset.update(application_urls=None)
                self.stdout.write("%d '%s' apphooks uninstalled\n" % (number_of_apphooks, label))
        else:
            self.stdout.write("no '%s' apphooks found\n" % label)

Example 11

Project: oh-mainline
Source File: __init__.py
View license
def create_superuser(app, created_models, verbosity, db, **kwargs):
    from django.core.management import call_command

    UserModel = get_user_model()

    if UserModel in created_models and kwargs.get('interactive', True):
        msg = ("\nYou just installed Django's auth system, which means you "
            "don't have any superusers defined.\nWould you like to create one "
            "now? (yes/no): ")
        confirm = input(msg)
        while 1:
            if confirm not in ('yes', 'no'):
                confirm = input('Please enter either "yes" or "no": ')
                continue
            if confirm == 'yes':
                call_command("createsuperuser", interactive=True, database=db)
            break

Example 12

Project: cgstudiomap
Source File: questioner.py
View license
    def _boolean_input(self, question, default=None):
        result = input("%s " % question)
        if not result and default is not None:
            return default
        while len(result) < 1 or result[0].lower() not in "yn":
            result = input("Please answer yes or no: ")
        return result[0].lower() == "y"

Example 13

Project: django
Source File: questioner.py
View license
    def _choice_input(self, question, choices):
        print(question)
        for i, choice in enumerate(choices):
            print(" %s) %s" % (i + 1, choice))
        result = input("Select an option: ")
        while True:
            try:
                value = int(result)
                if 0 < value <= len(choices):
                    return value
            except ValueError:
                pass
            result = input("Please select a valid option: ")

Example 14

Project: PyClassLessons
Source File: questioner.py
View license
    def _boolean_input(self, question, default=None):
        result = input("%s " % question)
        if not result and default is not None:
            return default
        while len(result) < 1 or result[0].lower() not in "yn":
            result = input("Please answer yes or no: ")
        return result[0].lower() == "y"

Example 15

Project: splunk-webframework
Source File: __init__.py
View license
def create_superuser(app, created_models, verbosity, db, **kwargs):
    from django.core.management import call_command

    UserModel = get_user_model()

    if UserModel in created_models and kwargs.get('interactive', True):
        msg = ("\nYou just installed Django's auth system, which means you "
            "don't have any superusers defined.\nWould you like to create one "
            "now? (yes/no): ")
        confirm = input(msg)
        while 1:
            if confirm not in ('yes', 'no'):
                confirm = input('Please enter either "yes" or "no": ')
                continue
            if confirm == 'yes':
                call_command("createsuperuser", interactive=True, database=db)
            break

Example 16

Project: HealthStarter
Source File: createsuperuser.py
View license
    def get_input_data(self, field, message, default=None):
        """
        Override this method if you want to customize data inputs or
        validation exceptions.
        """
        raw_value = input(message)
        if default and raw_value == '':
            raw_value = default
        try:
            val = field.clean(raw_value, None)
        except exceptions.ValidationError as e:
            self.stderr.write("Error: %s" % '; '.join(e.messages))
            val = None

        return val

Example 17

Project: oh-mainline
Source File: creation.py
View license
    def _create_test_db(self, verbosity, autoclobber):
        test_database_name = self._get_test_db_name()
        if test_database_name != ':memory:':
            # Erase the old test database
            if verbosity >= 1:
                print("Destroying old test database '%s'..." % self.connection.alias)
            if os.access(test_database_name, os.F_OK):
                if not autoclobber:
                    confirm = input("Type 'yes' if you would like to try deleting the test database '%s', or 'no' to cancel: " % test_database_name)
                if autoclobber or confirm == 'yes':
                    try:
                        os.remove(test_database_name)
                    except Exception as e:
                        sys.stderr.write("Got an error deleting the old test database: %s\n" % e)
                        sys.exit(2)
                else:
                    print("Tests cancelled.")
                    sys.exit(1)
        return test_database_name

Example 18

Project: Misago
Source File: remakemisagochecksums.py
View license
    def handle(self, *args, **options):
        message = force_str("This will replace all checksums "
                            "in database with new ones, marking "
                            "all data as trusted. Are you sure "
                            "you wish to continue? [Y/n]")
        if '--force' in args or input(message).strip().lower() == "y":
            self.stdout.write("\nRegenerating checksums...")
            secret_key_changed.send(self)
            self.stdout.write("\nDone!")
        else:
            self.stdout.write("\nAborted!")

Example 19

Project: Spirit
Source File: spirittx.py
View license
    def handle(self, *args, **options):
        # todo: test!
        # Requires "pip install transifex-client==0.11"

        call_command('spirittxpull', stdout=self.stdout, stderr=self.stderr)
        call_command('spiritmakelocales', stdout=self.stdout, stderr=self.stderr)
        message = (
            "Push is destructive, please review "
            "the locale changes, run `$ git diff`\n"
            "Do you want to push the changes? y/n: "
        )

        if input(message).lower() == "y":
            call_command('spirittxpush', stdout=self.stdout, stderr=self.stderr)

        self.stdout.write('ok')

Example 20

Project: django
Source File: questioner.py
View license
    def _boolean_input(self, question, default=None):
        result = input("%s " % question)
        if not result and default is not None:
            return default
        while len(result) < 1 or result[0].lower() not in "yn":
            result = input("Please answer yes or no: ")
        return result[0].lower() == "y"

Example 21

Project: HealthStarter
Source File: questioner.py
View license
    def _boolean_input(self, question, default=None):
        result = input("%s " % question)
        if not result and default is not None:
            return default
        while len(result) < 1 or result[0].lower() not in "yn":
            result = input("Please answer yes or no: ")
        return result[0].lower() == "y"

Example 22

Project: decode-Django
Source File: creation.py
View license
    def _create_test_db(self, verbosity, autoclobber):
        test_database_name = self._get_test_db_name()
        if test_database_name != ':memory:':
            # Erase the old test database
            if verbosity >= 1:
                print("Destroying old test database '%s'..." % self.connection.alias)
            if os.access(test_database_name, os.F_OK):
                if not autoclobber:
                    confirm = input("Type 'yes' if you would like to try deleting the test database '%s', or 'no' to cancel: " % test_database_name)
                if autoclobber or confirm == 'yes':
                    try:
                        os.remove(test_database_name)
                    except Exception as e:
                        sys.stderr.write("Got an error deleting the old test database: %s\n" % e)
                        sys.exit(2)
                else:
                    print("Tests cancelled.")
                    sys.exit(1)
        return test_database_name

Example 23

Project: HealthStarter
Source File: questioner.py
View license
    def _choice_input(self, question, choices):
        print(question)
        for i, choice in enumerate(choices):
            print(" %s) %s" % (i + 1, choice))
        result = input("Select an option: ")
        while True:
            try:
                value = int(result)
                if 0 < value <= len(choices):
                    return value
            except ValueError:
                pass
            result = input("Please select a valid option: ")

Example 24

View license
    def get_input_data(self, field, message, default=None):
        """
        Override this method if you want to customize data inputs or
        validation exceptions.
        """
        raw_value = input(message)
        if default and raw_value == '':
            raw_value = default
        try:
            val = field.clean(raw_value, None)
        except exceptions.ValidationError as e:
            self.stderr.write("Error: %s" % '; '.join(e.messages))
            val = None

        return val

Example 25

Project: cgstudiomap
Source File: questioner.py
View license
    def _choice_input(self, question, choices):
        print(question)
        for i, choice in enumerate(choices):
            print(" %s) %s" % (i + 1, choice))
        result = input("Select an option: ")
        while True:
            try:
                value = int(result)
                if 0 < value <= len(choices):
                    return value
            except ValueError:
                pass
            result = input("Please select a valid option: ")

Example 26

View license
    def _boolean_input(self, question, default=None):
        result = input("%s " % question)
        if not result and default is not None:
            return default
        while len(result) < 1 or result[0].lower() not in "yn":
            result = input("Please answer yes or no: ")
        return result[0].lower() == "y"

Example 27

Project: splunk-webframework
Source File: creation.py
View license
    def _create_test_db(self, verbosity, autoclobber):
        test_database_name = self._get_test_db_name()
        if test_database_name != ':memory:':
            # Erase the old test database
            if verbosity >= 1:
                print("Destroying old test database '%s'..." % self.connection.alias)
            if os.access(test_database_name, os.F_OK):
                if not autoclobber:
                    confirm = input("Type 'yes' if you would like to try deleting the test database '%s', or 'no' to cancel: " % test_database_name)
                if autoclobber or confirm == 'yes':
                    try:
                        os.remove(test_database_name)
                    except Exception as e:
                        sys.stderr.write("Got an error deleting the old test database: %s\n" % e)
                        sys.exit(2)
                else:
                    print("Tests cancelled.")
                    sys.exit(1)
        return test_database_name

Example 28

Project: treeherder
Source File: init_datasources.py
View license
    def handle(self, *args, **options):
        if options["reset"]:
            confirm = input("""You have requested an init of the datasources.
This will IRREVERSIBLY DESTROY all data in the per-project databases.
Are you sure you want to do this?

Type 'yes' to continue, or 'no' to cancel: """)
            if confirm == "yes":
                for ds in Datasource.objects.all():
                    ds.delete()

        projects = Repository.objects.filter(active_status='active').values_list('name', flat=True)
        for project in projects:
            Datasource.objects.get_or_create(project=project)
        Datasource.reset_cache()

Example 29

Project: golismero
Source File: creation.py
View license
    def _create_test_db(self, verbosity, autoclobber):
        test_database_name = self._get_test_db_name()
        if test_database_name != ':memory:':
            # Erase the old test database
            if verbosity >= 1:
                print("Destroying old test database '%s'..." % self.connection.alias)
            if os.access(test_database_name, os.F_OK):
                if not autoclobber:
                    confirm = input("Type 'yes' if you would like to try deleting the test database '%s', or 'no' to cancel: " % test_database_name)
                if autoclobber or confirm == 'yes':
                    try:
                        os.remove(test_database_name)
                    except Exception as e:
                        sys.stderr.write("Got an error deleting the old test database: %s\n" % e)
                        sys.exit(2)
                else:
                    print("Tests cancelled.")
                    sys.exit(1)
        return test_database_name

Example 30

Project: hue
Source File: creation.py
View license
    def _create_test_db(self, verbosity, autoclobber):
        test_database_name = self._get_test_db_name()
        if test_database_name != ':memory:':
            # Erase the old test database
            if verbosity >= 1:
                print("Destroying old test database '%s'..." % self.connection.alias)
            if os.access(test_database_name, os.F_OK):
                if not autoclobber:
                    confirm = input("Type 'yes' if you would like to try deleting the test database '%s', or 'no' to cancel: " % test_database_name)
                if autoclobber or confirm == 'yes':
                    try:
                        os.remove(test_database_name)
                    except Exception as e:
                        sys.stderr.write("Got an error deleting the old test database: %s\n" % e)
                        sys.exit(2)
                else:
                    print("Tests cancelled.")
                    sys.exit(1)
        return test_database_name

Example 31

Project: cgstudiomap
Source File: createsuperuser.py
View license
    def get_input_data(self, field, message, default=None):
        """
        Override this method if you want to customize data inputs or
        validation exceptions.
        """
        raw_value = input(message)
        if default and raw_value == '':
            raw_value = default
        try:
            val = field.clean(raw_value, None)
        except exceptions.ValidationError as e:
            self.stderr.write("Error: %s" % '; '.join(e.messages))
            val = None

        return val

Example 32

Project: django-hashbrown
Source File: switches.py
View license
def ask_permission(stderr, switches):
    stderr.write('The following switches are in the database but not in %s:' % SETTINGS_KEY)

    for label in switches:
        stderr.write(label)

    response = input('Delete switches? [y/N]: ')

    return response.lower().strip() in ('y', 'yes')

Example 33

View license
    def handle(self, **options):

        self.verbosity = options.get('verbosity')
        self.interactive = options.get('interactive')
        app_label = options['app_label']
        migration_name = options['migration_name']
        no_optimize = options['no_optimize']

        # Load the current graph state, check the app and migration they asked for exists
        executor = MigrationExecutor(connections[DEFAULT_DB_ALIAS])
        if app_label not in executor.loader.migrated_apps:
            raise CommandError(
                "App '%s' does not have migrations (so squashmigrations on "
                "it makes no sense)" % app_label
            )
        try:
            migration = executor.loader.get_migration_by_prefix(app_label, migration_name)
        except AmbiguityError:
            raise CommandError(
                "More than one migration matches '%s' in app '%s'. Please be "
                "more specific." % (migration_name, app_label)
            )
        except KeyError:
            raise CommandError(
                "Cannot find a migration matching '%s' from app '%s'." %
                (migration_name, app_label)
            )

        # Work out the list of predecessor migrations
        migrations_to_squash = [
            executor.loader.get_migration(al, mn)
            for al, mn in executor.loader.graph.forwards_plan((migration.app_label, migration.name))
            if al == migration.app_label
        ]

        # Tell them what we're doing and optionally ask if we should proceed
        if self.verbosity > 0 or self.interactive:
            self.stdout.write(self.style.MIGRATE_HEADING("Will squash the following migrations:"))
            for migration in migrations_to_squash:
                self.stdout.write(" - %s" % migration.name)

            if self.interactive:
                answer = None
                while not answer or answer not in "yn":
                    answer = six.moves.input("Do you wish to proceed? [yN] ")
                    if not answer:
                        answer = "n"
                        break
                    else:
                        answer = answer[0].lower()
                if answer != "y":
                    return

        # Load the operations from all those migrations and concat together,
        # along with collecting external dependencies and detecting
        # double-squashing
        operations = []
        dependencies = set()
        for smigration in migrations_to_squash:
            if smigration.replaces:
                raise CommandError(
                    "You cannot squash squashed migrations! Please transition "
                    "it to a normal migration first: "
                    "https://docs.djangoproject.com/en/%s/topics/migrations/#squashing-migrations" % get_docs_version()
                )
            operations.extend(smigration.operations)
            for dependency in smigration.dependencies:
                if isinstance(dependency, SwappableTuple):
                    if settings.AUTH_USER_MODEL == dependency.setting:
                        dependencies.add(("__setting__", "AUTH_USER_MODEL"))
                    else:
                        dependencies.add(dependency)
                elif dependency[0] != smigration.app_label:
                    dependencies.add(dependency)

        if no_optimize:
            if self.verbosity > 0:
                self.stdout.write(self.style.MIGRATE_HEADING("(Skipping optimization.)"))
            new_operations = operations
        else:
            if self.verbosity > 0:
                self.stdout.write(self.style.MIGRATE_HEADING("Optimizing..."))

            optimizer = MigrationOptimizer()
            new_operations = optimizer.optimize(operations, migration.app_label)

            if self.verbosity > 0:
                if len(new_operations) == len(operations):
                    self.stdout.write("  No optimizations possible.")
                else:
                    self.stdout.write(
                        "  Optimized from %s operations to %s operations." %
                        (len(operations), len(new_operations))
                    )

        # Work out the value of replaces (any squashed ones we're re-squashing)
        # need to feed their replaces into ours
        replaces = []
        for migration in migrations_to_squash:
            if migration.replaces:
                replaces.extend(migration.replaces)
            else:
                replaces.append((migration.app_label, migration.name))

        # Make a new migration with those operations
        subclass = type("Migration", (migrations.Migration, ), {
            "dependencies": dependencies,
            "operations": new_operations,
            "replaces": replaces,
        })
        new_migration = subclass("0001_squashed_%s" % migration.name, app_label)

        # Write out the new migration file
        writer = MigrationWriter(new_migration)
        with open(writer.path, "wb") as fh:
            fh.write(writer.as_string())

        if self.verbosity > 0:
            self.stdout.write(self.style.MIGRATE_HEADING("Created new squashed migration %s" % writer.path))
            self.stdout.write("  You should commit this migration but leave the old ones in place;")
            self.stdout.write("  the new migration will be used for new installs. Once you are sure")
            self.stdout.write("  all instances of the codebase have applied the migrations you squashed,")
            self.stdout.write("  you can delete them.")
            if writer.needs_manual_porting:
                self.stdout.write(self.style.MIGRATE_HEADING("Manual porting required"))
                self.stdout.write("  Your migrations contained functions that must be manually copied over,")
                self.stdout.write("  as we could not safely copy their implementation.")
                self.stdout.write("  See the comment at the top of the squashed migration for details.")

Example 34

Project: PyClassLessons
Source File: creation.py
View license
    def _handle_objects_preventing_db_destruction(self, cursor, parameters, verbosity, autoclobber):
        # There are objects in the test tablespace which prevent dropping it
        # The easy fix is to drop the test user -- but are we allowed to do so?
        print("There are objects in the old test database which prevent its destruction.")
        print("If they belong to the test user, deleting the user will allow the test "
              "database to be recreated.")
        print("Otherwise, you will need to find and remove each of these objects, "
              "or use a different tablespace.\n")
        if self._test_user_create():
            if not autoclobber:
                confirm = input("Type 'yes' to delete user %s: " % parameters['user'])
            if autoclobber or confirm == 'yes':
                try:
                    if verbosity >= 1:
                        print("Destroying old test user...")
                    self._destroy_test_user(cursor, parameters, verbosity)
                except Exception as e:
                    sys.stderr.write("Got an error destroying the test user: %s\n" % e)
                    sys.exit(2)
                try:
                    if verbosity >= 1:
                        print("Destroying old test database '%s'..." % self.connection.alias)
                    self._execute_test_db_destruction(cursor, parameters, verbosity)
                except Exception as e:
                    sys.stderr.write("Got an error destroying the test database: %s\n" % e)
                    sys.exit(2)
            else:
                print("Tests cancelled -- test database cannot be recreated.")
                sys.exit(1)
        else:
            print("Django is configured to use pre-existing test user '%s',"
                  " and will not attempt to delete it.\n" % parameters['user'])
            print("Tests cancelled -- test database cannot be recreated.")
            sys.exit(1)

Example 35

Project: Django--an-app-at-a-time
Source File: syncdb.py
View license
    def handle(self, **options):
        warnings.warn("The syncdb command will be removed in Django 1.9", RemovedInDjango19Warning)
        call_command("migrate", **options)

        try:
            apps.get_model('auth', 'Permission')
        except LookupError:
            return

        UserModel = get_user_model()

        if not UserModel._default_manager.exists() and options.get('interactive'):
            msg = ("\nYou have installed Django's auth system, and "
                "don't have any superusers defined.\nWould you like to create one "
                "now? (yes/no): ")
            confirm = input(msg)
            while 1:
                if confirm not in ('yes', 'no'):
                    confirm = input('Please enter either "yes" or "no": ')
                    continue
                if confirm == 'yes':
                    call_command("createsuperuser", interactive=True, database=options['database'])
                break

Example 36

Project: PyClassLessons
Source File: createsuperuser.py
View license
    def handle(self, *args, **options):
        username = options.get(self.UserModel.USERNAME_FIELD, None)
        interactive = options.get('interactive')
        verbosity = int(options.get('verbosity', 1))
        database = options.get('database')

        # If not provided, create the user with an unusable password
        password = None
        user_data = {}

        # Do quick and dirty validation if --noinput
        if not interactive:
            try:
                if not username:
                    raise CommandError("You must use --%s with --noinput." %
                            self.UserModel.USERNAME_FIELD)
                username = self.username_field.clean(username, None)

                for field_name in self.UserModel.REQUIRED_FIELDS:
                    if options.get(field_name):
                        field = self.UserModel._meta.get_field(field_name)
                        user_data[field_name] = field.clean(options[field_name], None)
                    else:
                        raise CommandError("You must use --%s with --noinput." % field_name)
            except exceptions.ValidationError as e:
                raise CommandError('; '.join(e.messages))

        else:
            # Prompt for username/password, and any other required fields.
            # Enclose this whole thing in a try/except to trap for a
            # keyboard interrupt and exit gracefully.
            default_username = get_default_username()
            try:

                if hasattr(self.stdin, 'isatty') and not self.stdin.isatty():
                    raise NotRunningInTTYException("Not running in a TTY")

                # Get a username
                verbose_field_name = self.username_field.verbose_name
                while username is None:
                    if not username:
                        input_msg = capfirst(verbose_field_name)
                        if default_username:
                            input_msg = "%s (leave blank to use '%s')" % (
                                input_msg, default_username)
                        raw_value = input(force_str('%s: ' % input_msg))

                    if default_username and raw_value == '':
                        raw_value = default_username
                    try:
                        username = self.username_field.clean(raw_value, None)
                    except exceptions.ValidationError as e:
                        self.stderr.write("Error: %s" % '; '.join(e.messages))
                        username = None
                        continue
                    try:
                        self.UserModel._default_manager.db_manager(database).get_by_natural_key(username)
                    except self.UserModel.DoesNotExist:
                        pass
                    else:
                        self.stderr.write("Error: That %s is already taken." %
                                verbose_field_name)
                        username = None

                for field_name in self.UserModel.REQUIRED_FIELDS:
                    field = self.UserModel._meta.get_field(field_name)
                    user_data[field_name] = options.get(field_name)
                    while user_data[field_name] is None:
                        raw_value = input(force_str('%s: ' % capfirst(field.verbose_name)))
                        try:
                            user_data[field_name] = field.clean(raw_value, None)
                        except exceptions.ValidationError as e:
                            self.stderr.write("Error: %s" % '; '.join(e.messages))
                            user_data[field_name] = None

                # Get a password
                while password is None:
                    if not password:
                        password = getpass.getpass()
                        password2 = getpass.getpass(force_str('Password (again): '))
                        if password != password2:
                            self.stderr.write("Error: Your passwords didn't match.")
                            password = None
                            continue
                    if password.strip() == '':
                        self.stderr.write("Error: Blank passwords aren't allowed.")
                        password = None
                        continue

            except KeyboardInterrupt:
                self.stderr.write("\nOperation cancelled.")
                sys.exit(1)

            except NotRunningInTTYException:
                self.stdout.write(
                    "Superuser creation skipped due to not running in a TTY. "
                    "You can run `manage.py createsuperuser` in your project "
                    "to create one manually."
                )

        if username:
            user_data[self.UserModel.USERNAME_FIELD] = username
            user_data['password'] = password
            self.UserModel._default_manager.db_manager(database).create_superuser(**user_data)
            if verbosity >= 1:
                self.stdout.write("Superuser created successfully.")

Example 37

View license
    def _create_test_db(self, verbosity, autoclobber, keepdb=False):
        """
        Internal implementation - creates the test db tables.
        """
        suffix = self.sql_table_creation_suffix()

        test_database_name = self._get_test_db_name()

        qn = self.connection.ops.quote_name

        # Create the test database and connect to it.
        with self._nodb_connection.cursor() as cursor:
            try:
                cursor.execute(
                    "CREATE DATABASE %s %s" % (qn(test_database_name), suffix))
            except Exception as e:
                # if we want to keep the db, then no need to do any of the below,
                # just return and skip it all.
                if keepdb:
                    return test_database_name

                sys.stderr.write(
                    "Got an error creating the test database: %s\n" % e)
                if not autoclobber:
                    confirm = input(
                        "Type 'yes' if you would like to try deleting the test "
                        "database '%s', or 'no' to cancel: " % test_database_name)
                if autoclobber or confirm == 'yes':
                    try:
                        if verbosity >= 1:
                            print("Destroying old test database '%s'..."
                                  % self.connection.alias)
                        cursor.execute(
                            "DROP DATABASE %s" % qn(test_database_name))
                        cursor.execute(
                            "CREATE DATABASE %s %s" % (qn(test_database_name),
                                                       suffix))
                    except Exception as e:
                        sys.stderr.write(
                            "Got an error recreating the test database: %s\n" % e)
                        sys.exit(2)
                else:
                    print("Tests cancelled.")
                    sys.exit(1)

        return test_database_name

Example 38

View license
    def _create_test_db(self, verbosity=1, autoclobber=False, keepdb=False):
        parameters = self._get_test_db_params()
        cursor = self.connection.cursor()
        if self._test_database_create():
            try:
                self._execute_test_db_creation(cursor, parameters, verbosity)
            except Exception as e:
                # if we want to keep the db, then no need to do any of the below,
                # just return and skip it all.
                if keepdb:
                    return
                sys.stderr.write("Got an error creating the test database: %s\n" % e)
                if not autoclobber:
                    confirm = input(
                        "It appears the test database, %s, already exists. "
                        "Type 'yes' to delete it, or 'no' to cancel: " % parameters['user'])
                if autoclobber or confirm == 'yes':
                    if verbosity >= 1:
                        print("Destroying old test database '%s'..." % self.connection.alias)
                    try:
                        self._execute_test_db_destruction(cursor, parameters, verbosity)
                    except DatabaseError as e:
                        if 'ORA-29857' in str(e):
                            self._handle_objects_preventing_db_destruction(cursor, parameters,
                                                                           verbosity, autoclobber)
                        else:
                            # Ran into a database error that isn't about leftover objects in the tablespace
                            sys.stderr.write("Got an error destroying the old test database: %s\n" % e)
                            sys.exit(2)
                    except Exception as e:
                        sys.stderr.write("Got an error destroying the old test database: %s\n" % e)
                        sys.exit(2)
                    try:
                        self._execute_test_db_creation(cursor, parameters, verbosity)
                    except Exception as e:
                        sys.stderr.write("Got an error recreating the test database: %s\n" % e)
                        sys.exit(2)
                else:
                    print("Tests cancelled.")
                    sys.exit(1)

        if self._test_user_create():
            if verbosity >= 1:
                print("Creating test user...")
            try:
                self._create_test_user(cursor, parameters, verbosity)
            except Exception as e:
                sys.stderr.write("Got an error creating the test user: %s\n" % e)
                if not autoclobber:
                    confirm = input(
                        "It appears the test user, %s, already exists. Type "
                        "'yes' to delete it, or 'no' to cancel: " % parameters['user'])
                if autoclobber or confirm == 'yes':
                    try:
                        if verbosity >= 1:
                            print("Destroying old test user...")
                        self._destroy_test_user(cursor, parameters, verbosity)
                        if verbosity >= 1:
                            print("Creating test user...")
                        self._create_test_user(cursor, parameters, verbosity)
                    except Exception as e:
                        sys.stderr.write("Got an error recreating the test user: %s\n" % e)
                        sys.exit(2)
                else:
                    print("Tests cancelled.")
                    sys.exit(1)

        self.connection.close()  # done with main user -- test user and tablespaces created

        real_settings = settings.DATABASES[self.connection.alias]
        real_settings['SAVED_USER'] = self.connection.settings_dict['SAVED_USER'] = \
            self.connection.settings_dict['USER']
        real_settings['SAVED_PASSWORD'] = self.connection.settings_dict['SAVED_PASSWORD'] = \
            self.connection.settings_dict['PASSWORD']
        real_test_settings = real_settings['TEST']
        test_settings = self.connection.settings_dict['TEST']
        real_test_settings['USER'] = real_settings['USER'] = test_settings['USER'] = \
            self.connection.settings_dict['USER'] = parameters['user']
        real_settings['PASSWORD'] = self.connection.settings_dict['PASSWORD'] = parameters['password']

        return self.connection.settings_dict['NAME']

Example 39

Project: GAE-Bulk-Mailer
Source File: creation.py
View license
    def _create_test_db(self, verbosity=1, autoclobber=False):
        TEST_NAME = self._test_database_name()
        TEST_USER = self._test_database_user()
        TEST_PASSWD = self._test_database_passwd()
        TEST_TBLSPACE = self._test_database_tblspace()
        TEST_TBLSPACE_TMP = self._test_database_tblspace_tmp()

        parameters = {
            'dbname': TEST_NAME,
            'user': TEST_USER,
            'password': TEST_PASSWD,
            'tblspace': TEST_TBLSPACE,
            'tblspace_temp': TEST_TBLSPACE_TMP,
        }

        cursor = self.connection.cursor()
        if self._test_database_create():
            try:
                self._execute_test_db_creation(cursor, parameters, verbosity)
            except Exception as e:
                sys.stderr.write("Got an error creating the test database: %s\n" % e)
                if not autoclobber:
                    confirm = input("It appears the test database, %s, already exists. Type 'yes' to delete it, or 'no' to cancel: " % TEST_NAME)
                if autoclobber or confirm == 'yes':
                    try:
                        if verbosity >= 1:
                            print("Destroying old test database '%s'..." % self.connection.alias)
                        self._execute_test_db_destruction(cursor, parameters, verbosity)
                        self._execute_test_db_creation(cursor, parameters, verbosity)
                    except Exception as e:
                        sys.stderr.write("Got an error recreating the test database: %s\n" % e)
                        sys.exit(2)
                else:
                    print("Tests cancelled.")
                    sys.exit(1)

        if self._test_user_create():
            if verbosity >= 1:
                print("Creating test user...")
            try:
                self._create_test_user(cursor, parameters, verbosity)
            except Exception as e:
                sys.stderr.write("Got an error creating the test user: %s\n" % e)
                if not autoclobber:
                    confirm = input("It appears the test user, %s, already exists. Type 'yes' to delete it, or 'no' to cancel: " % TEST_USER)
                if autoclobber or confirm == 'yes':
                    try:
                        if verbosity >= 1:
                            print("Destroying old test user...")
                        self._destroy_test_user(cursor, parameters, verbosity)
                        if verbosity >= 1:
                            print("Creating test user...")
                        self._create_test_user(cursor, parameters, verbosity)
                    except Exception as e:
                        sys.stderr.write("Got an error recreating the test user: %s\n" % e)
                        sys.exit(2)
                else:
                    print("Tests cancelled.")
                    sys.exit(1)

        self.connection.settings_dict['SAVED_USER'] = self.connection.settings_dict['USER']
        self.connection.settings_dict['SAVED_PASSWORD'] = self.connection.settings_dict['PASSWORD']
        self.connection.settings_dict['TEST_USER'] = self.connection.settings_dict['USER'] = TEST_USER
        self.connection.settings_dict['PASSWORD'] = TEST_PASSWD

        return self.connection.settings_dict['NAME']

Example 40

Project: PyClassLessons
Source File: management.py
View license
def update_contenttypes(app_config, verbosity=2, interactive=True, using=DEFAULT_DB_ALIAS, **kwargs):
    """
    Creates content types for models in the given app, removing any model
    entries that no longer have a matching model class.
    """
    # TODO: Remove when migration plan / state is passed (#24100).
    if not is_latest_migration_applied('contenttypes'):
        return

    if not app_config.models_module:
        return

    try:
        ContentType = apps.get_model('contenttypes', 'ContentType')
    except LookupError:
        return

    if not router.allow_migrate(using, ContentType):
        return

    ContentType.objects.clear_cache()

    app_label = app_config.label

    app_models = dict(
        (model._meta.model_name, model)
        for model in app_config.get_models())

    if not app_models:
        return

    # Get all the content types
    content_types = dict(
        (ct.model, ct)
        for ct in ContentType.objects.using(using).filter(app_label=app_label)
    )
    to_remove = [
        ct
        for (model_name, ct) in six.iteritems(content_types)
        if model_name not in app_models
    ]

    cts = [
        ContentType(
            name=smart_text(model._meta.verbose_name_raw),
            app_label=app_label,
            model=model_name,
        )
        for (model_name, model) in six.iteritems(app_models)
        if model_name not in content_types
    ]
    ContentType.objects.using(using).bulk_create(cts)
    if verbosity >= 2:
        for ct in cts:
            print("Adding content type '%s | %s'" % (ct.app_label, ct.model))

    # Confirm that the content type is stale before deletion.
    if to_remove:
        if interactive:
            content_type_display = '\n'.join(
                '    %s | %s' % (ct.app_label, ct.model)
                for ct in to_remove
            )
            ok_to_delete = input("""The following content types are stale and need to be deleted:

%s

Any objects related to these content types by a foreign key will also
be deleted. Are you sure you want to delete these content types?
If you're unsure, answer 'no'.

    Type 'yes' to continue, or 'no' to cancel: """ % content_type_display)
        else:
            ok_to_delete = False

        if ok_to_delete == 'yes':
            for ct in to_remove:
                if verbosity >= 2:
                    print("Deleting stale content type '%s | %s'" % (ct.app_label, ct.model))
                ct.delete()
        else:
            if verbosity >= 2:
                print("Stale content types remain.")

Example 41

View license
    def _handle_objects_preventing_db_destruction(self, cursor, parameters, verbosity, autoclobber):
        # There are objects in the test tablespace which prevent dropping it
        # The easy fix is to drop the test user -- but are we allowed to do so?
        print("There are objects in the old test database which prevent its destruction.")
        print("If they belong to the test user, deleting the user will allow the test "
              "database to be recreated.")
        print("Otherwise, you will need to find and remove each of these objects, "
              "or use a different tablespace.\n")
        if self._test_user_create():
            if not autoclobber:
                confirm = input("Type 'yes' to delete user %s: " % parameters['user'])
            if autoclobber or confirm == 'yes':
                try:
                    if verbosity >= 1:
                        print("Destroying old test user...")
                    self._destroy_test_user(cursor, parameters, verbosity)
                except Exception as e:
                    sys.stderr.write("Got an error destroying the test user: %s\n" % e)
                    sys.exit(2)
                try:
                    if verbosity >= 1:
                        print("Destroying old test database '%s'..." % self.connection.alias)
                    self._execute_test_db_destruction(cursor, parameters, verbosity)
                except Exception as e:
                    sys.stderr.write("Got an error destroying the test database: %s\n" % e)
                    sys.exit(2)
            else:
                print("Tests cancelled -- test database cannot be recreated.")
                sys.exit(1)
        else:
            print("Django is configured to use pre-existing test user '%s',"
                  " and will not attempt to delete it.\n" % parameters['user'])
            print("Tests cancelled -- test database cannot be recreated.")
            sys.exit(1)

Example 42

View license
    def _create_test_db(self, verbosity, autoclobber, keepdb=False):
        test_database_name = self._get_test_db_name()

        if keepdb:
            return test_database_name
        if not self.connection.is_in_memory_db(test_database_name):
            # Erase the old test database
            if verbosity >= 1:
                print("Destroying old test database '%s'..." % self.connection.alias)
            if os.access(test_database_name, os.F_OK):
                if not autoclobber:
                    confirm = input(
                        "Type 'yes' if you would like to try deleting the test "
                        "database '%s', or 'no' to cancel: " % test_database_name
                    )
                if autoclobber or confirm == 'yes':
                    try:
                        os.remove(test_database_name)
                    except Exception as e:
                        sys.stderr.write("Got an error deleting the old test database: %s\n" % e)
                        sys.exit(2)
                else:
                    print("Tests cancelled.")
                    sys.exit(1)
        return test_database_name

Example 43

View license
    def _ask_default(self):
        print("Please enter the default value now, as valid Python")
        print("The datetime and django.utils.timezone modules are available, so you can do e.g. timezone.now()")
        while True:
            if six.PY3:
                # Six does not correctly abstract over the fact that
                # py3 input returns a unicode string, while py2 raw_input
                # returns a bytestring.
                code = input(">>> ")
            else:
                code = input(">>> ").decode(sys.stdin.encoding)
            if not code:
                print("Please enter some code, or 'exit' (with no quotes) to exit.")
            elif code == "exit":
                sys.exit(1)
            else:
                try:
                    return eval(code, {}, {"datetime": datetime_safe, "timezone": timezone})
                except (SyntaxError, NameError) as e:
                    print("Invalid input: %s" % e)

Example 44

Project: PyClassLessons
Source File: questioner.py
View license
    def _ask_default(self):
        print("Please enter the default value now, as valid Python")
        print("The datetime and django.utils.timezone modules are available, so you can do e.g. timezone.now()")
        while True:
            if six.PY3:
                # Six does not correctly abstract over the fact that
                # py3 input returns a unicode string, while py2 raw_input
                # returns a bytestring.
                code = input(">>> ")
            else:
                code = input(">>> ").decode(sys.stdin.encoding)
            if not code:
                print("Please enter some code, or 'exit' (with no quotes) to exit.")
            elif code == "exit":
                sys.exit(1)
            else:
                try:
                    return eval(code, {}, {"datetime": datetime_safe, "timezone": timezone})
                except (SyntaxError, NameError) as e:
                    print("Invalid input: %s" % e)

Example 45

View license
    def handle(self, *args, **options):
        media_path = ""

        if len(args):
            media_path = args[0]
            path = media_path
        else:
            path = DIRECTORY

        if not os.path.isdir(os.path.join(settings.MEDIA_ROOT, path)):
            raise CommandError('<media_path> must be a directory in MEDIA_ROOT (If you don\'t add a media_path the default path is DIRECTORY).\n"%s" is no directory.' % path)

        # get version name
        while 1:
            self.stdout.write('\nSelect a version you want to generate:\n')
            for version in VERSIONS:
                self.stdout.write(' * %s\n' % version)

            version_name = input('(leave blank to generate all versions): ')

            if version_name == "":
                selected_version = None
                break
            else:
                try:
                    tmp = VERSIONS[version_name]
                    selected_version = version_name
                    break
                except:
                    self.stderr.write('Error: Version "%s" doesn\'t exist.\n' % version_name)
                    version_name = None
                    continue

        # filelisting
        filelisting = FileListing(path, filter_func=self.filter_images)  # FIXME filterfunc: no hidden files, exclude list, no versions, just images!
        for fileobject in filelisting.files_walk_filtered():
            if fileobject.filetype == "Image":
                if selected_version:
                    self.stdout.write('generating version "%s" for: %s\n' % (selected_version, fileobject.path))
                    versionobject = fileobject.version_generate(selected_version)  # FIXME force?
                else:
                    self.stdout.write('generating all versions for: %s\n' % fileobject.path)
                    for version in VERSIONS:
                        versionobject = fileobject.version_generate(version)  # FIXME force?

Example 46

View license
    def handle(self, *args, **options):

        media_path = ""

        if len(args):
            media_path = args[0]

        path = os.path.join(settings.MEDIA_ROOT, media_path)

        if not os.path.isdir(path):
            raise CommandError('<media_path> must be a directory in MEDIA_ROOT. "%s" is no directory.' % path)

        self.stdout.write("\n%s\n" % self.help)
        self.stdout.write("in this case: %s\n" % path)

        # get suffix or prefix
        default_prefix_or_suffix = "s"
        while 1:
            self.stdout.write('\nOlder versions of the FileBrowser used to prefix the filename with the version name.\n')
            self.stdout.write('Current version of the FileBrowser adds the version name as suffix.\n')
            prefix_or_suffix = input('"p" for prefix or "s" for suffix (leave blank for "%s"): ' % default_prefix_or_suffix)

            if default_prefix_or_suffix and prefix_or_suffix == '':
                prefix_or_suffix = default_prefix_or_suffix
            if prefix_or_suffix != "s" and prefix_or_suffix != "p":
                sys.stderr.write('Error: "p" and "s" are the only valid inputs.\n')
                prefix_or_suffix = None
                continue
            break

        # get version name
        while 1:
            version_name = input('\nversion name as defined with VERSIONS: ')

            if version_name == "":
                self.stderr.write('Error: You have to enter a version name.\n')
                version_name = None
                continue
            else:
                break

        # get list of all matching files
        files = self.get_files(path, version_name, (prefix_or_suffix == "p"))

        # output (short version) of files to be deleted
        if len(files) > 15:
            self.stdout.write('\nFirst/Last 5 files to remove:\n')
            for current_file in files[:5]:
                self.stdout.write('%s\n' % current_file)
            self.stdout.write('...\n')
            self.stdout.write('...\n')
            for current_file in files[len(files) - 5:]:
                self.stdout.write('%s\n' % current_file)
        else:
            self.stdout.write('\nFiles to remove:\n')
            for current_file in files:
                self.stdout.write('%s\n' % current_file)

        # no files...done
        if len(files) == 0:
            self.stdout.write('0 files removed.\n\n')
            return
        else:
            self.stdout.write('%d file(s) will be removed.\n\n' % len(files))

        # ask to make sure
        do_remove = ""
        self.stdout.write('Are Sure you want to delete these files?\n')
        do_remove = input('"y" for Yes or "n" for No (leave blank for "n"): ')

        # if "yes" we delete. any different case we finish without removing anything
        if do_remove == "y":
            for current_file in files:
                os.remove(current_file)
            self.stdout.write('%d file(s) removed.\n\n' % len(files))
        else:
            self.stdout.write('No files removed.\n\n')
        return

Example 47

Project: PyClassLessons
Source File: collectstatic.py
View license
    def handle_noargs(self, **options):
        self.set_options(**options)

        message = ['\n']
        if self.dry_run:
            message.append(
                'You have activated the --dry-run option so no files will be modified.\n\n'
            )

        message.append(
            'You have requested to collect static files at the destination\n'
            'location as specified in your settings'
        )

        if self.is_local_storage() and self.storage.location:
            destination_path = self.storage.location
            message.append(':\n\n    %s\n\n' % destination_path)
        else:
            destination_path = None
            message.append('.\n\n')

        if self.clear:
            message.append('This will DELETE EXISTING FILES!\n')
        else:
            message.append('This will overwrite existing files!\n')

        message.append(
            'Are you sure you want to do this?\n\n'
            "Type 'yes' to continue, or 'no' to cancel: "
        )

        if self.interactive and input(''.join(message)) != 'yes':
            raise CommandError("Collecting static files cancelled.")

        collected = self.collect()
        modified_count = len(collected['modified'])
        unmodified_count = len(collected['unmodified'])
        post_processed_count = len(collected['post_processed'])

        if self.verbosity >= 1:
            template = ("\n%(modified_count)s %(identifier)s %(action)s"
                        "%(destination)s%(unmodified)s%(post_processed)s.\n")
            summary = template % {
                'modified_count': modified_count,
                'identifier': 'static file' + ('' if modified_count == 1 else 's'),
                'action': 'symlinked' if self.symlink else 'copied',
                'destination': (" to '%s'" % destination_path if destination_path else ''),
                'unmodified': (', %s unmodified' % unmodified_count if collected['unmodified'] else ''),
                'post_processed': (collected['post_processed'] and
                                   ', %s post-processed'
                                   % post_processed_count or ''),
            }
            self.stdout.write(summary)

Example 48

Project: pythondotorg
Source File: load_dev_fixtures.py
View license
    def handle_noargs(self, **options):

        # Confirm the user wants to do this
        confirm = input("""You have requested to load the python.org development fixtures.
This will IRREVERSIBLY DESTROY all data currently in your local database.
Are you sure you want to do this?

    Type 'y' or 'yes' to continue, 'n' or 'no' to cancel:  """)

        if confirm in ('y', 'yes'):
            self.stdout.write("\nBeginning download, note this can take a couple of minutes...")
            r = requests.get(settings.DEV_FIXTURE_URL, stream=True)

            if r.status_code != 200:
                self.stderr.write("Unable to download file: Received status code {}".format(r.status_code))
                sys.exit(1)

            # Remove pesky objects that get in the way
            Permission.objects.all().delete()
            ContentType.objects.all().delete()

            with open('/tmp/dev-fixtures.json.gz', 'wb') as f:
                for chunk in r.iter_content(chunk_size=1024):
                    f.write(chunk)
                    f.flush()

            self.stdout.write("Download complete, loading fixtures")
            call_command('loaddata', '/tmp/dev-fixtures.json')
            self.stdout.write("END: Fixtures loaded")

Example 49

View license
    def handle(self, *args, **options):
        username = options.get(self.UserModel.USERNAME_FIELD, None)
        interactive = options.get('interactive')
        verbosity = int(options.get('verbosity', 1))
        database = options.get('database')

        # If not provided, create the user with an unusable password
        password = None
        user_data = {}

        # Do quick and dirty validation if --noinput
        if not interactive:
            try:
                if not username:
                    raise CommandError("You must use --%s with --noinput." %
                            self.UserModel.USERNAME_FIELD)
                username = self.username_field.clean(username, None)

                for field_name in self.UserModel.REQUIRED_FIELDS:
                    if options.get(field_name):
                        field = self.UserModel._meta.get_field(field_name)
                        user_data[field_name] = field.clean(options[field_name], None)
                    else:
                        raise CommandError("You must use --%s with --noinput." % field_name)
            except exceptions.ValidationError as e:
                raise CommandError('; '.join(e.messages))

        else:
            # Prompt for username/password, and any other required fields.
            # Enclose this whole thing in a try/except to trap for a
            # keyboard interrupt and exit gracefully.
            default_username = get_default_username()
            try:

                # Get a username
                verbose_field_name = force_text(self.username_field.verbose_name)
                while username is None:
                    if not username:
                        input_msg = capfirst(verbose_field_name)
                        if default_username:
                            input_msg = "%s (leave blank to use '%s')" % (
                                input_msg, default_username)
                        raw_value = input(force_str('%s: ' % input_msg))

                    if default_username and raw_value == '':
                        raw_value = default_username
                    try:
                        username = self.username_field.clean(raw_value, None)
                    except exceptions.ValidationError as e:
                        self.stderr.write("Error: %s" % '; '.join(e.messages))
                        username = None
                        continue
                    try:
                        self.UserModel._default_manager.db_manager(database).get_by_natural_key(username)
                    except self.UserModel.DoesNotExist:
                        pass
                    else:
                        self.stderr.write("Error: That %s is already taken." %
                                verbose_field_name)
                        username = None

                for field_name in self.UserModel.REQUIRED_FIELDS:
                    field = self.UserModel._meta.get_field(field_name)
                    user_data[field_name] = options.get(field_name)
                    while user_data[field_name] is None:
                        raw_value = input(force_str('%s: ' % capfirst(force_text(field.verbose_name))))
                        try:
                            user_data[field_name] = field.clean(raw_value, None)
                        except exceptions.ValidationError as e:
                            self.stderr.write("Error: %s" % '; '.join(e.messages))
                            user_data[field_name] = None

                # Get a password
                while password is None:
                    if not password:
                        password = getpass.getpass()
                        password2 = getpass.getpass(force_str('Password (again): '))
                        if password != password2:
                            self.stderr.write("Error: Your passwords didn't match.")
                            password = None
                            continue
                    if password.strip() == '':
                        self.stderr.write("Error: Blank passwords aren't allowed.")
                        password = None
                        continue

            except KeyboardInterrupt:
                self.stderr.write("\nOperation cancelled.")
                sys.exit(1)

        user_data[self.UserModel.USERNAME_FIELD] = username
        user_data['password'] = password
        self.UserModel._default_manager.db_manager(database).create_superuser(**user_data)
        if verbosity >= 1:
            self.stdout.write("Superuser created successfully.")

Example 50

Project: splunk-webframework
Source File: management.py
View license
def update_contenttypes(app, created_models, verbosity=2, db=DEFAULT_DB_ALIAS, **kwargs):
    """
    Creates content types for models in the given app, removing any model
    entries that no longer have a matching model class.
    """
    if not router.allow_syncdb(db, ContentType):
        return

    ContentType.objects.clear_cache()
    app_models = get_models(app)
    if not app_models:
        return
    # They all have the same app_label, get the first one.
    app_label = app_models[0]._meta.app_label
    app_models = dict(
        (model._meta.object_name.lower(), model)
        for model in app_models
    )

    # Get all the content types
    content_types = dict(
        (ct.model, ct)
        for ct in ContentType.objects.using(db).filter(app_label=app_label)
    )
    to_remove = [
        ct
        for (model_name, ct) in six.iteritems(content_types)
        if model_name not in app_models
    ]

    cts = [
        ContentType(
            name=smart_text(model._meta.verbose_name_raw),
            app_label=app_label,
            model=model_name,
        )
        for (model_name, model) in six.iteritems(app_models)
        if model_name not in content_types
    ]
    ContentType.objects.using(db).bulk_create(cts)
    if verbosity >= 2:
        for ct in cts:
            print("Adding content type '%s | %s'" % (ct.app_label, ct.model))

    # Confirm that the content type is stale before deletion.
    if to_remove:
        if kwargs.get('interactive', False):
            content_type_display = '\n'.join([
                '    %s | %s' % (ct.app_label, ct.model)
                for ct in to_remove
            ])
            ok_to_delete = input("""The following content types are stale and need to be deleted:

%s

Any objects related to these content types by a foreign key will also
be deleted. Are you sure you want to delete these content types?
If you're unsure, answer 'no'.

    Type 'yes' to continue, or 'no' to cancel: """ % content_type_display)
        else:
            ok_to_delete = False

        if ok_to_delete == 'yes':
            for ct in to_remove:
                if verbosity >= 2:
                    print("Deleting stale content type '%s | %s'" % (ct.app_label, ct.model))
                ct.delete()
        else:
            if verbosity >= 2:
                print("Stale content types remain.")