def forwards(self, orm): # make sure any pending db records are created, # since loading permissions requires access to content types db.send_pending_create_signals() # verbosity, interactive ? # use django load_data to load the fixture from django.core.management import call_command call_command('loaddata', 'site_admin_group')
def forwards(self, orm): "Write your forwards methods here." # See https://groups.google.com/forum/?fromgroups=#!topic/south-users/ZmmUyrrRoYU or groups:0006_add_group_perms db.send_pending_create_signals() self.modify_perms(orm, lambda perms, perm: perms.add(perm))
def forwards(self, orm): if not db.dry_run: # some object classes can only be seen by root, like all users for # instance. Add the new object class RegistrationRequest to the group # which all project admins are part of, so they don't get a 403 forbidden # when trying to see requests for their project try: projectadmins = Group.objects.get(name="projectadmins") except Group.DoesNotExist as e: projectadmins = Group(name="projectadmins") # TODO add permissions for all comicmodels and registrationRequest projectadmins.save() # my god spent 2 hours on this line. But this fixes any issues with # default permissions for registrationrequest not being found.. db.send_pending_create_signals() # each user in comic is part of this group projectadmins. With the # permission in this group you can determine which types of objects # regular adins can see and edit in the admin interface. self.add_standard_perms("comicmodels", "registrationrequest", projectadmins) self.add_standard_perms("comicmodels", "comicsite", projectadmins) self.add_standard_perms("comicmodels", "page", projectadmins)
def forwards(self, orm): db.send_pending_create_signals() ct = orm['contenttypes.ContentType'].objects.get( app_label='attachments', model='attachment') for p in self.permissions: perm, created = orm['auth.permission'].objects.get_or_create( content_type=ct, codename=p[0], defaults=dict(name=p[1]))
def forwards(self, orm): "Write your forwards methods here." db.send_pending_create_signals() util.migrations.migrate_groups_forwards(orm, auth_groups, ) user_manager = django.contrib.auth.models.User.objects groupadmin_user, created = user_manager.get_or_create(username='******', defaults={'password':'******'}) groupadmin_group = django.contrib.auth.models.Group.objects.get(name='system:groupadmin') groupadmin_user.groups.add(groupadmin_group)
def forwards(self, orm): "Write your forwards methods here." # Create the various contenttypes and permissions and stuff # Otherwise the permission stuff will fail horribly # http://groups.google.com/group/south-users/browse_thread/thread/666994cabad1a185?pli=1 db.send_pending_create_signals() util.migrations.migrate_perms_forwards(orm, self.new_perms, ) util.migrations.migrate_groups_forwards(orm, self.new_auth_groups, )
def forwards(self, orm): #send signal post_syncdb so that permissions will be created even if the corresponding model was created in this migration db.send_pending_create_signals() "Write your forwards methods here." group = orm['auth.group'].objects.get_or_create(name="Trainer")[0] permissions =orm['auth.Permission'].objects.filter(codename=u'change_solution') group.permissions.add(*permissions) group.save()
def migrate_many(self, target, migrations): try: for migration in migrations: result = self.migrate(migration) if result is False: # The migrations errored, but nicely. return False finally: # Call any pending post_syncdb signals db.send_pending_create_signals() return True
def forwards(self, orm): "Write your forwards methods here." # Force create content types, since by default south wouldn't create # them until it finished running migrations. db.send_pending_create_signals() ct = orm['contenttypes.ContentType'].objects.get(app_label='wiki', model='document') for p in self.permissions: perm, created = orm['auth.permission'].objects.get_or_create( content_type=ct, codename=p[0], defaults=dict(name=p[1]))
def forwards(self, orm): """ Creating group called ambasadors and adding permissions to it """ transaction.set_autocommit(True) try: db.send_pending_create_signals() orm['auth.Group'].objects.create(name='ambassadors') finally: transaction.set_autocommit(False)
def forwards(self, orm): "Write your forwards methods here." # Create the various contenttypes and permissions and stuff # Otherwise the we'll end with a group without a name # http://groups.google.com/group/south-users/browse_thread/thread/666994cabad1a185?pli=1 db.send_pending_create_signals() # See http://stackoverflow.com/questions/1742021/adding-new-custom-permissions-in-django#answer-6149593 ct, created = orm["contenttypes.ContentType"].objects.get_or_create( model="group", app_label="groups" ) # model must be lowercase! for codename, verbose_name in self.new_perms: perm, created = orm["auth.permission"].objects.get_or_create( content_type=ct, codename=codename, defaults={"name": verbose_name} )
def forwards(self, orm): # send signal post_syncdb so that permissions will be created even if the corresponding model was created in this migration db.send_pending_create_signals() depends_on = (("accounts", "0002_load_initial_data"),) trainer = orm["auth.group"].objects.get_or_create(name="Trainer")[0] permissions = orm["auth.Permission"].objects.filter(codename__in=[u"change_chunk", "change_settings"]) trainer.permissions.add(*permissions) trainer.save() orm.Settings().save() orm.Chunk(key="Welcome Message").save() orm.Chunk(key="Login Message").save()
def forwards(self, orm): #send signal post_syncdb so that permissions will be created even if the corresponding model was created in this migration db.send_pending_create_signals() depends_on = (("accounts", "0002_load_initial_data"), ) trainer = orm['auth.group'].objects.get_or_create(name="Trainer")[0] permissions = orm['auth.Permission'].objects.filter( codename__in=[u'change_chunk', 'change_settings']) trainer.permissions.add(*permissions) trainer.save() orm.Settings().save() orm.Chunk(key='Welcome Message').save() orm.Chunk(key='Login Message').save()
def forwards(self, orm): """ Creating group called ambasadors and adding permissions to it """ transaction.set_autocommit(True) try: db.send_pending_create_signals() group = orm['auth.Group'].objects.create(name='ambassadors') permission_codes = ['edit_event', 'submit_event', 'reject_event'] for code in permission_codes: permission = orm['auth.Permission'].objects.get(codename=code) group.permissions.add(permission) group.save() finally: transaction.set_autocommit(False)
def forwards(self, orm): '''Load a fixture with initial flatpages content, and update the Site Admin group with permissions to create, edit, and delete flatpages. ''' # make sure any pending db records are created, # loading permissions requires access to content types db.send_pending_create_signals() # verbosity, interactive ? # use django load_data to load the fixture from django.core.management import call_command call_command('loaddata', 'initial_flatpages') try: admin_grp = Group.objects.get(name='Site Admin') flatpage_perms = Permission.objects.filter(codename__contains='flatpage') admin_grp.permissions.add(*flatpage_perms) admin_grp.save() except Group.DoesNotExist: logger.warn('Could not find Site Admin group to update permissions')
def forwards(self, orm): # Adding model 'RegistrationRequest' db.create_table(u'comicmodels_registrationrequest', ( (u'id', self.gf('django.db.models.fields.AutoField')(primary_key=True)), ('user', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['auth.User'])), ('project', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['comicmodels.ComicSite'])), ('created', self.gf('django.db.models.fields.DateTimeField')(default=datetime.date.today, auto_now_add=True, blank=True)), ('changed', self.gf('django.db.models.fields.DateTimeField')(null=True, blank=True)), ('status', self.gf('django.db.models.fields.CharField')(default='PEND', max_length=4)), )) db.send_create_signal(u'comicmodels', ['RegistrationRequest']) # Adding field 'ComicSite.require_participant_review' db.add_column(u'comicmodels_comicsite', 'require_participant_review', self.gf('django.db.models.fields.BooleanField')(default=False), keep_default=False) db.send_pending_create_signals()
def forwards(self, orm): "Write your forwards methods here." # Note: Remember to use orm['appname.ModelName'] rather than "from appname.models..." Place = orm['sa_api_v2.Place'] Activity = orm['sa_api_v2.Activity'] ContentType = orm['contenttypes.ContentType'] # Need to do this before we can use ContentTypes. db.send_pending_create_signals() place_type = ContentType.objects.get(name='place', app_label='sa_api_v2') for place in Place.objects.all(): activity = Activity(data_content_type=place_type, data_object_id=place.id, created_datetime=place.created_datetime, updated_datetime=place.created_datetime) activity.save()
def forwards(self, orm): "Write your forwards methods here." # Note: Remember to use orm['appname.ModelName'] rather than "from appname.models..." Place = orm['sa_api.Place'] Activity = orm['sa_api.Activity'] ContentType = orm['contenttypes.ContentType'] # Need to do this before we can use ContentTypes. db.send_pending_create_signals() place_type = ContentType.objects.get(name='place', app_label='sa_api') for place in Place.objects.all(): activity = Activity(data_content_type=place_type, data_object_id=place.id, created_datetime=place.created_datetime, updated_datetime=place.created_datetime) activity.save()
def forwards(self, orm): '''Load a fixture with initial flatpages content, and update the Site Admin group with permissions to create, edit, and delete flatpages. ''' # make sure any pending db records are created, # loading permissions requires access to content types db.send_pending_create_signals() # verbosity, interactive ? # use django load_data to load the fixture from django.core.management import call_command call_command('loaddata', 'initial_flatpages') try: admin_grp = Group.objects.get(name='Site Admin') flatpage_perms = Permission.objects.filter( codename__contains='flatpage') admin_grp.permissions.add(*flatpage_perms) admin_grp.save() except Group.DoesNotExist: logger.warn( 'Could not find Site Admin group to update permissions')
def forwards(self, orm): #send signal post_syncdb so that permissions will be created even if the corresponding model was created in this migration db.send_pending_create_signals() group = orm['auth.group'].objects.get_or_create(name="Trainer")[0] permissions =orm['auth.Permission'].objects.filter(codename__in=[ u'add_tutorial', u'change_tutorial', u'delete_tutorial', u'add_userprofile', u'change_userprofile', u'delete_userprofile', u'add_rating', u'change_rating', u'delete_rating', u'add_ratingaspect', u'change_ratingaspect', u'delete_ratingaspect', u'add_ratingscale', u'change_ratingscale', u'delete_ratingscale', u'add_ratingscaleitem', u'change_ratingscaleitem', u'delete_ratingscaleitem', u'add_user', u'change_user', u'delete_user', u'add_mediafile', u'change_mediafile', u'delete_mediafile', u'add_task', u'change_task', u'delete_task']) group.permissions.add(*permissions) group.save() orm['auth.group'].objects.get_or_create(name="Tutor")[0].save() orm['auth.group'].objects.get_or_create(name="User")[0].save()
def forwards(self, orm): db.send_pending_create_signals() ct = ContentType.objects.get(app_label="grading", model="student") see, __ = Permission.objects.get_or_create( codename = "can_see_students_data", name = "Can see students_data", content_type = ct) grade, __ = Permission.objects.get_or_create( codename = "can_grade", name = "Can grade", content_type = ct) teachers, __ = Group.objects.get_or_create(name="teachers") teachers.permissions.add(see) teachers.permissions.add(grade) Group.objects.get_or_create(name="students") teachers.save()
def forwards(self, orm): #send signal post_syncdb so that permissions will be created even if the corresponding model was created in this migration db.send_pending_create_signals() group = orm['auth.group'].objects.get_or_create(name="Trainer")[0] permissions = orm['auth.Permission'].objects.filter(codename__in=[ u'add_tutorial', u'change_tutorial', u'delete_tutorial', u'add_userprofile', u'change_userprofile', u'delete_userprofile', u'add_rating', u'change_rating', u'delete_rating', u'add_ratingaspect', u'change_ratingaspect', u'delete_ratingaspect', u'add_ratingscale', u'change_ratingscale', u'delete_ratingscale', u'add_ratingscaleitem', u'change_ratingscaleitem', u'delete_ratingscaleitem', u'add_user', u'change_user', u'delete_user', u'add_mediafile', u'change_mediafile', u'delete_mediafile', u'add_task', u'change_task', u'delete_task' ]) group.permissions.add(*permissions) group.save() orm['auth.group'].objects.get_or_create(name="Tutor")[0].save() orm['auth.group'].objects.get_or_create(name="User")[0].save()
def forwards(self, orm): # Adding model 'ManyToManyValue' db.create_table('philo_manytomanyvalue', ( ('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)), ('content_type', self.gf('django.db.models.fields.related.ForeignKey')(blank=True, related_name='many_to_many_value_set', null=True, to=orm['contenttypes.ContentType'])), ('object_ids', self.gf('django.db.models.fields.CommaSeparatedIntegerField')(max_length=300, null=True, blank=True)), )) db.send_create_signal('philo', ['ManyToManyValue']) # Adding model 'JSONValue' db.create_table('philo_jsonvalue', ( ('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)), ('value', self.gf('philo.models.fields.JSONField')()), )) db.send_create_signal('philo', ['JSONValue']) # Adding model 'ForeignKeyValue' db.create_table('philo_foreignkeyvalue', ( ('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)), ('content_type', self.gf('django.db.models.fields.related.ForeignKey')(blank=True, related_name='foreign_key_value_set', null=True, to=orm['contenttypes.ContentType'])), ('object_id', self.gf('django.db.models.fields.PositiveIntegerField')(null=True, blank=True)), )) db.send_create_signal('philo', ['ForeignKeyValue']) # Adding field 'Attribute.value_content_type' db.add_column('philo_attribute', 'value_content_type', self.gf('django.db.models.fields.related.ForeignKey')(blank=True, related_name='attribute_value_set', null=True, to=orm['contenttypes.ContentType']), keep_default=False) # Adding field 'Attribute.value_object_id' db.add_column('philo_attribute', 'value_object_id', self.gf('django.db.models.fields.PositiveIntegerField')(null=True, blank=True), keep_default=False) # Adding unique constraint on 'Attribute', fields ['value_object_id', 'value_content_type'] db.create_unique('philo_attribute', ['value_object_id', 'value_content_type_id']) # Manual addition! This is necessary to immediately cause contenttype creation. # (needed for the next migration) db.send_pending_create_signals()
def forwards(self, orm): # Adding model 'PublicDocument' db.create_table('fccpublicfiles_publicdocument', ( ('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)), ('station', self.gf('django.db.models.fields.CharField')(max_length=12)), ('documentcloud_doc', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['doccloud.Document'])), )) db.send_create_signal('fccpublicfiles', ['PublicDocument']) # Adding model 'Address' db.create_table('fccpublicfiles_address', ( ('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)), ('address1', self.gf('django.db.models.fields.CharField')(max_length=100, null=True, blank=True)), ('address2', self.gf('django.db.models.fields.CharField')(max_length=100, null=True, blank=True)), ('city', self.gf('django.db.models.fields.CharField')(max_length=50)), ('state', self.gf('django.contrib.localflavor.us.models.USStateField')(max_length=2)), ('zipcode', self.gf('django.db.models.fields.CharField')(max_length=10, null=True, blank=True)), )) db.send_create_signal('fccpublicfiles', ['Address']) # Adding model 'Person' db.create_table('fccpublicfiles_person', ( ('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)), ('first_name', self.gf('django.db.models.fields.CharField')(max_length=40)), ('middle_name', self.gf('django.db.models.fields.CharField')(max_length=40, null=True, blank=True)), ('last_name', self.gf('django.db.models.fields.CharField')(max_length=40)), ('suffix', self.gf('django.db.models.fields.CharField')(max_length=10, null=True, blank=True)), )) db.send_create_signal('fccpublicfiles', ['Person']) # Adding model 'Role' db.create_table('fccpublicfiles_role', ( ('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)), ('person', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['fccpublicfiles.Person'])), ('organization', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['fccpublicfiles.Organization'])), ('title', self.gf('django.db.models.fields.CharField')(max_length=100)), )) db.send_create_signal('fccpublicfiles', ['Role']) # Adding model 'Organization' db.create_table('fccpublicfiles_organization', ( ('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)), ('name', self.gf('django.db.models.fields.CharField')(max_length=100)), ('organization_type', self.gf('django.db.models.fields.CharField')(max_length=2, blank=True)), ('fec_id', self.gf('django.db.models.fields.CharField')(max_length=9, blank=True)), )) db.send_create_signal('fccpublicfiles', ['Organization']) # Adding M2M table for field addresses on 'Organization' db.create_table('fccpublicfiles_organization_addresses', ( ('id', models.AutoField(verbose_name='ID', primary_key=True, auto_created=True)), ('organization', models.ForeignKey(orm['fccpublicfiles.organization'], null=False)), ('address', models.ForeignKey(orm['fccpublicfiles.address'], null=False)) )) db.create_unique('fccpublicfiles_organization_addresses', ['organization_id', 'address_id']) # Adding model 'PoliticalBuy' db.create_table('fccpublicfiles_politicalbuy', ( ('publicdocument_ptr', self.gf('django.db.models.fields.related.OneToOneField')(to=orm['fccpublicfiles.PublicDocument'], unique=True, primary_key=True)), ('contract_number', self.gf('django.db.models.fields.CharField')(max_length=100, blank=True)), ('advertiser', self.gf('django.db.models.fields.related.ForeignKey')(blank=True, related_name='advertiser_politicalbuys', null=True, to=orm['fccpublicfiles.Organization'])), ('advertiser_signatory', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['fccpublicfiles.Person'], null=True, blank=True)), ('bought_by', self.gf('django.db.models.fields.related.ForeignKey')(blank=True, related_name='mediabuyer_politicalbuys', null=True, to=orm['fccpublicfiles.Organization'])), ('contract_start_date', self.gf('django.db.models.fields.DateField')(default=datetime.datetime(2012, 6, 13, 0, 0), null=True, blank=True)), ('contract_end_date', self.gf('django.db.models.fields.DateField')(default=datetime.datetime(2012, 6, 13, 0, 0), null=True, blank=True)), ('lowest_unit_price', self.gf('django.db.models.fields.NullBooleanField')(default=None, null=True, blank=True)), )) db.send_create_signal('fccpublicfiles', ['PoliticalBuy']) # Adding model 'PoliticalSpot' db.create_table('fccpublicfiles_politicalspot', ( ('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)), ('document', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['fccpublicfiles.PoliticalBuy'])), ('airing_start_date', self.gf('django.db.models.fields.DateField')(null=True, blank=True)), ('airing_end_date', self.gf('django.db.models.fields.DateField')(null=True, blank=True)), ('airing_days', self.gf('weekday_field.fields.WeekdayField')(max_length=14, blank=True)), ('timeslot_begin', self.gf('django.db.models.fields.TimeField')(null=True, blank=True)), ('timeslot_end', self.gf('django.db.models.fields.TimeField')(null=True, blank=True)), ('show_name', self.gf('django.db.models.fields.CharField')(max_length=100, blank=True)), ('broadcast_length', self.gf('timedelta.fields.TimedeltaField')(null=True, blank=True)), ('num_spots', self.gf('django.db.models.fields.IntegerField')(null=True, blank=True)), ('rate', self.gf('django.db.models.fields.DecimalField')(null=True, max_digits=9, decimal_places=2, blank=True)), ('preemptable', self.gf('django.db.models.fields.NullBooleanField')(default=None, null=True, blank=True)), )) db.send_create_signal('fccpublicfiles', ['PoliticalSpot']) db.send_pending_create_signals()
def migrate_app(app, tree, target_name=None, resolve_mode=None, fake=False, db_dry_run=False, yes=False, verbosity=0, load_inital_data=False, skip=False): app_name = get_app_name(app) verbosity = int(verbosity) db.debug = (verbosity > 1) # Fire off the pre-migrate signal pre_migrate.send(None, app=app_name) # Find out what delightful migrations we have migrations = get_migration_names(app) # If there aren't any, quit quizically if not migrations: print "? You have no migrations for the '%s' app. You might want some." % app_name return if target_name not in migrations and target_name not in ["zero", None]: matches = [x for x in migrations if x.startswith(target_name)] if len(matches) == 1: target = migrations.index(matches[0]) + 1 if verbosity: print " - Soft matched migration %s to %s." % ( target_name, matches[0] ) target_name = matches[0] elif len(matches) > 1: if verbosity: print " - Prefix %s matches more than one migration:" % target_name print " " + "\n ".join(matches) return else: print " ! '%s' is not a migration." % target_name return # Check there's no strange ones in the database ghost_migrations = [] for m in MigrationHistory.objects.filter(applied__isnull = False): try: if get_app(m.app_name) not in tree or m.migration not in tree[get_app(m.app_name)]: ghost_migrations.append(m) except ImproperlyConfigured: pass if ghost_migrations: print " ! These migrations are in the database but not on disk:" print " - " + "\n - ".join(["%s: %s" % (x.app_name, x.migration) for x in ghost_migrations]) print " ! I'm not trusting myself; fix this yourself by fiddling" print " ! with the south_migrationhistory table." return # Say what we're doing if verbosity: print "Running migrations for %s:" % app_name # Get the forwards and reverse dependencies for this target if target_name == None: target_name = migrations[-1] if target_name == "zero": forwards = [] backwards = needed_before_backwards(tree, app, migrations[0]) + [(app, migrations[0])] else: forwards = needed_before_forwards(tree, app, target_name) + [(app, target_name)] # When migrating backwards we want to remove up to and including # the next migration up in this app (not the next one, that includes other apps) try: migration_before_here = migrations[migrations.index(target_name)+1] backwards = needed_before_backwards(tree, app, migration_before_here) + [(app, migration_before_here)] except IndexError: backwards = [] # Get the list of currently applied migrations from the db current_migrations = [] for m in MigrationHistory.objects.filter(applied__isnull = False): try: current_migrations.append((get_app(m.app_name), m.migration)) except ImproperlyConfigured: pass direction = None bad = False # Work out the direction applied_for_this_app = list(MigrationHistory.objects.filter(app_name=app_name, applied__isnull=False).order_by("migration")) if target_name == "zero": direction = -1 elif not applied_for_this_app: direction = 1 elif migrations.index(target_name) > migrations.index(applied_for_this_app[-1].migration): direction = 1 elif migrations.index(target_name) < migrations.index(applied_for_this_app[-1].migration): direction = -1 else: direction = None # Is the whole forward branch applied? missing = [step for step in forwards if step not in current_migrations] # If they're all applied, we only know it's not backwards if not missing: direction = None # If the remaining migrations are strictly a right segment of the forwards # trace, we just need to go forwards to our target (and check for badness) else: problems = forwards_problems(tree, forwards, current_migrations, verbosity=verbosity) if problems: bad = True direction = 1 # What about the whole backward trace then? if not bad: missing = [step for step in backwards if step not in current_migrations] # If they're all missing, stick with the forwards decision if missing == backwards: pass # If what's missing is a strict left segment of backwards (i.e. # all the higher migrations) then we need to go backwards else: problems = backwards_problems(tree, backwards, current_migrations, verbosity=verbosity) if problems: bad = True direction = -1 if bad and resolve_mode not in ['merge'] and not skip: print " ! Inconsistent migration history" print " ! The following options are available:" print " --merge: will just attempt the migration ignoring any potential dependency conflicts." sys.exit(1) if direction == 1: if verbosity: print " - Migrating forwards to %s." % target_name try: for mapp, mname in forwards: if (mapp, mname) not in current_migrations: result = run_forwards(mapp, [mname], fake=fake, db_dry_run=db_dry_run, verbosity=verbosity) if result is False: # The migrations errored, but nicely. return False finally: # Call any pending post_syncdb signals db.send_pending_create_signals() # Now load initial data, only if we're really doing things and ended up at current if not fake and not db_dry_run and load_inital_data and target_name == migrations[-1]: if verbosity: print " - Loading initial data for %s." % app_name # Override Django's get_apps call temporarily to only load from the # current app old_get_apps, models.get_apps = ( models.get_apps, lambda: [models.get_app(get_app_name(app))], ) # Load the initial fixture call_command('loaddata', 'initial_data', verbosity=verbosity) # Un-override models.get_apps = old_get_apps elif direction == -1: if verbosity: print " - Migrating backwards to just after %s." % target_name for mapp, mname in backwards: if (mapp, mname) in current_migrations: run_backwards(mapp, [mname], fake=fake, db_dry_run=db_dry_run, verbosity=verbosity) else: if verbosity: print "- Nothing to migrate." # Finally, fire off the post-migrate signal post_migrate.send(None, app=app_name)
def forwards(self, orm): db.send_pending_create_signals() # First, create the ParliamentarySession objects. (If there # are already parliamentary sessions, then don't try to create # any new ones.) na1_kenya = None na2_kenya = None senate = None house = None if 0 == orm.ParliamentarySession.objects.count(): if settings.COUNTRY_APP == 'kenya': governmental, _ = orm.OrganisationKind.objects.get_or_create( name='Governmental', slug='governmental') ok_na, _ = orm.Organisation.objects.get_or_create(name='Parliament', slug='parliament', kind=governmental) ok_senate, _ = orm.Organisation.objects.get_or_create(name='Senate', slug='senate', kind=governmental) na1_kenya = orm.ParliamentarySession(name="National Assembly 2007-2013", slug='na2007', start_date=datetime.date(2007, 12, 28), end_date=datetime.date(2013, 1, 14), mapit_generation=2, house=ok_na) na1_kenya.save() na2_kenya = orm.ParliamentarySession(name="National Assembly 2013-", slug='na2013', start_date=datetime.date(2013, 3, 5), end_date=datetime.date(9999, 12, 31), mapit_generation=3, house=ok_na) na2_kenya.save() senate = orm.ParliamentarySession(name="Senate 2013-", slug='s2013', start_date=datetime.date(2013, 3, 5), end_date=datetime.date(9999, 12, 31), mapit_generation=3, house=ok_senate) senate.save() elif settings.COUNTRY_APP == 'nigeria': political, _ = orm.OrganisationKind.objects.get_or_create( name='Political', slug='political') ok_senate, _ = orm.Organisation.objects.get_or_create(name='Senate', slug='senate', kind=political) ok_house, _ = orm.Organisation.objects.get_or_create(name='House of Representatives', slug='house-of-representatives', kind=political) senate = orm.ParliamentarySession(name="Senate 2011-", slug='s2011', start_date=datetime.date(2011, 4, 10), end_date=datetime.date(9999, 12, 31), mapit_generation=1, house=ok_senate) senate.save() house = orm.ParliamentarySession(name="House of Representatives 2011-", slug='hr2011', start_date=datetime.date(2011, 04, 10), end_date=datetime.date(9999, 12, 31), mapit_generation=1, house=ok_house) house.save() else: # There's nothing to do: print >> sys.stderr, "Unknown COUNTRY_APP (%s) - not creating parliamentary sessions" % (settings.COUNTRY_APP,) else: # There's nothing to do: print >> sys.stderr, "There were already ParliamentarySessions - skipping their creation" # Now link each Place to the right ParliamentarySession: if settings.COUNTRY_APP == 'kenya': pk_constituency, _ = orm.PlaceKind.objects.get_or_create(slug='constituency', name='Constituency', plural_name='Constituencies') pk_2013_constituency, _ = orm.PlaceKind.objects.get_or_create(slug='2013-constituency', name='2013 Constituency', plural_name='2013 Constituencies') pk_county, _ = orm.PlaceKind.objects.get_or_create(slug='county', name='County', plural_name='Counties') if not na1_kenya: na1_kenya = orm.ParliamentarySession.objects.get(name="National Assembly 2007-2013") if not na2_kenya: na2_kenya = orm.ParliamentarySession.objects.get(name="National Assembly 2013-") if not senate: senate = orm.ParliamentarySession.objects.get(name="Senate 2013-") for place in pk_constituency.place_set.all(): if place.name == 'Mbeere South': print >> sys.stderr, "Skipping Mbeere South, which shouldn't be there" place.parliamentary_session = na1_kenya place.save() for place in pk_2013_constituency.place_set.all(): place.parliamentary_session = na2_kenya place.kind = pk_constituency place.save() for place in pk_county.place_set.all(): place.parliamentary_session = senate place.save() # We don't need the '2013 Constituencies' PlaceKind any # more, so remove it: pk_2013_constituency.delete() elif settings.COUNTRY_APP == 'nigeria': if not house: house = orm.ParliamentarySession.objects.get(name="House of Representatives 2011-") if not senate: senate = orm.ParliamentarySession.objects.get(name="Senate 2011-") pk_fed, _ = orm.PlaceKind.objects.get_or_create(slug='federal-constituency', name='Federal Constituency', plural_name='Federal Constituencies') pk_sen, _ = orm.PlaceKind.objects.get_or_create(slug='senatorial-district', name='Senatorial District', plural_name='Senatorial Districts') for place in pk_fed.place_set.all(): place.parliamentary_session = house place.save() for place in pk_sen.place_set.all(): place.parliamentary_session = senate place.save() else: # There's nothing to do: print >> sys.stderr, "Unknown COUNTRY_APP (%s) - not linking sessions to places" % (settings.COUNTRY_APP,)
def forwards(self, orm): # Adding model 'ManyToManyValue' db.create_table('philo_manytomanyvalue', ( ('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)), ('content_type', self.gf('django.db.models.fields.related.ForeignKey')( blank=True, related_name='many_to_many_value_set', null=True, to=orm['contenttypes.ContentType'])), ('object_ids', self.gf('django.db.models.fields.CommaSeparatedIntegerField')( max_length=300, null=True, blank=True)), )) db.send_create_signal('philo', ['ManyToManyValue']) # Adding model 'JSONValue' db.create_table('philo_jsonvalue', ( ('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)), ('value', self.gf('philo.models.fields.JSONField')()), )) db.send_create_signal('philo', ['JSONValue']) # Adding model 'ForeignKeyValue' db.create_table('philo_foreignkeyvalue', ( ('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)), ('content_type', self.gf('django.db.models.fields.related.ForeignKey')( blank=True, related_name='foreign_key_value_set', null=True, to=orm['contenttypes.ContentType'])), ('object_id', self.gf('django.db.models.fields.PositiveIntegerField')( null=True, blank=True)), )) db.send_create_signal('philo', ['ForeignKeyValue']) # Adding field 'Attribute.value_content_type' db.add_column('philo_attribute', 'value_content_type', self.gf('django.db.models.fields.related.ForeignKey')( blank=True, related_name='attribute_value_set', null=True, to=orm['contenttypes.ContentType']), keep_default=False) # Adding field 'Attribute.value_object_id' db.add_column('philo_attribute', 'value_object_id', self.gf('django.db.models.fields.PositiveIntegerField')( null=True, blank=True), keep_default=False) # Adding unique constraint on 'Attribute', fields ['value_object_id', 'value_content_type'] db.create_unique('philo_attribute', ['value_object_id', 'value_content_type_id']) # Manual addition! This is necessary to immediately cause contenttype creation. # (needed for the next migration) db.send_pending_create_signals()