From 6f4774ae9ee119336a9d7320897cecac054b0d26 Mon Sep 17 00:00:00 2001 From: Christopher Charbonneau Wells Date: Sun, 20 Aug 2017 09:44:44 -0400 Subject: [PATCH] Add "reset" management command for resetting the database with fake data. --- babyblotter/management/commands/reset.py | 66 ++++++++++++++++++++++++ 1 file changed, 66 insertions(+) create mode 100644 babyblotter/management/commands/reset.py diff --git a/babyblotter/management/commands/reset.py b/babyblotter/management/commands/reset.py new file mode 100644 index 00000000..e10ae624 --- /dev/null +++ b/babyblotter/management/commands/reset.py @@ -0,0 +1,66 @@ +# -*- coding: utf-8 -*- +from __future__ import unicode_literals + +from django.apps import apps +from django.contrib.auth import get_user_model +from django.core.management.base import BaseCommand, CommandError +from django.core.management.commands.flush import Command as Flush +from django.core.management.commands.migrate import Command as Migrate + +from .fake import Command as Fake + + +class Command(BaseCommand): + help = 'Reapplies core migrations and generates fake data.' + + def __init__(self, *args, **kwargs): + super(Command, self).__init__(*args, **kwargs) + self.UserModel = get_user_model() + self.username_field = self.UserModel._meta.get_field( + self.UserModel.USERNAME_FIELD) + + def add_arguments(self, parser): + Migrate().add_arguments(parser) + Fake().add_arguments(parser) + + def handle(self, *args, **options): + verbosity = options['verbosity'] + database = options['database'] + + flush = Flush() + flush.handle(**options) + if verbosity > 0: + self.stdout.write(self.style.SUCCESS('Database flushed.')) + + for config in apps.app_configs.values(): + if config.path.split('/')[-2] == 'babyblotter': + migrate = Migrate() + options['app_label'] = config.name + options['migration_name'] = 'zero' + + try: + migrate.handle(*args, **options) + except CommandError: + # Ignore apps without migrations. + pass + + migrate = Migrate() + options['app_label'] = None + options['migration_name'] = None + migrate.handle(*args, **options) + + self.UserModel._default_manager.db_manager(database).create_superuser( + **{ + self.UserModel.USERNAME_FIELD: 'admin', + 'email': 'admin@admin.admin', + 'password': 'admin' + } + ) + if options['verbosity'] > 0: + self.stdout.write('Superuser created successfully.') + + fake = Fake() + fake.handle(*args, **options) + + if verbosity > 0: + self.stdout.write(self.style.SUCCESS('Database reset complete.'))