Example #1
0
    def handle(self, *args, **options):

        office_kind = OrganisationKind.objects.get(slug='constituency-office')

        if len(args) != 1:
            self.print_help(sys.argv[0], sys.argv[1])
            return

        office_id = args[0]

        if not options['new_address']:
            raise CommandError('You must supply --address')

        if (options['lat'] is None) ^ (options['lon'] is None):
            raise CommandError('You must supply both --lat and --lon')

        try:
            office = Organisation.objects.get(pk=office_id)
        except Organisation.DoesNotExist:
            raise CommandError("No office found with ID {0}".format(office_id))

        self.stdout.write("Updating the constituency office: " +
                          office.name.encode('utf-8'))

        if office.kind != office_kind:
            raise CommandError(
                "Organisation {0} isn't a constituency office".format(
                    office_id))

        if options['lat']:
            lon = options['lon']
            lat = options['lat']
        else:
            # Otherwise try to geocode the address:
            try:
                lon, lat, _ = geocode(options['new_address'])
                print "Location found"
            except LocationNotFound:
                raise CommandError(
                    u"Couldn't find the location of:\n{0}".format(
                        options['new_address']))

        # Check with the user if this is actually the location they
        # want:

        url_template = 'https://www.google.com/maps/place/{lat}+{lon}/@{lat},{lon},17z'
        print "This would update the office address to:"
        print ' ', url_template.format(lon=lon, lat=lat)
        print "If this is correct, type 'y' to continue:"
        response = raw_input('(y/n): ')
        if response != 'y':
            sys.stderr.write("Aborting.\n")
            return

        existing_positions = office.place_set.filter(
            kind__slug='constituency-office',
            name__startswith='Approximate position')
        if len(existing_positions) > 1:
            msg = "Bad data: found multiple existing positions for the office"
            raise CommandError(msg)
        elif len(existing_positions) == 0:
            # Create a new position:
            position_name = u'Approximate position of ' + office.name
            position = Place(
                name=position_name,
                organisation=office,
                slug=slugify(position_name),
                location=Point(lon, lat),
                kind=PlaceKind.objects.get(slug='constituency-office'),
            )
        else:
            # Update the existing position:
            position = existing_positions[0]
            position.location = Point(lon, lat)

        existing_addresses = office.contacts.filter(kind__slug='address')
        if len(existing_addresses) > 1:
            msg = "Bad data: found multiple existing addresses for the office"
            raise CommandError(msg)
        elif len(existing_addresses) == 0:
            contact_address = Contact(
                value=options['new_address'],
                kind=ContactKind.objects.get(slug='address'),
            )
        else:
            contact_address = existing_addresses[0]
            contact_address.value = options['new_address']

        # Actually save to the database (or not, depending on whether
        # --commit was specified).

        if options['commit']:
            print "Saving to the database:"
        else:
            msg = "Not updating (--commit wasn't specified) but would save:"
            self.stdout.write(msg)
        self.stdout.write('Place: ' + unicode(position).encode('utf-8'))
        self.stdout.write('Contact: ' +
                          unicode(contact_address).encode('utf-8'))

        if options['commit']:
            position.save()
            contact_address.save()
    def handle_label(self,  input_filename, **options):

        next_session = ParliamentarySession.objects.get(slug='na2013')

        # Get (or create) the PlaceKind for wards:

        try:
            ward_place_kind = PlaceKind.objects.get(slug='ward')
        except PlaceKind.DoesNotExist:
            ward_place_kind = PlaceKind(slug="ward",
                                         name="Ward",
                                         plural_name="Wards")
            name = str(ward_place_kind).encode('utf-8')
            if options['commit']:
                print >> sys.stderr, "Saving", name
                ward_place_kind.save()
            else:
                print >> sys.stderr, "Not saving", name, "because --commit wasn't specified"

        with open(input_filename) as fp:

            reader = csv.reader(fp)
            for row in reader:
                # The column headings change at various points in the
                # file, so save them when they appear:
                if re.search('County No', row[0]):
                    headings = [c.strip() for c in row]
                else:
                    # Otherwise create a dictionary that maps headings
                    # to column values:
                    row_dict = dict(zip(headings, (c.strip() for c in row)))
                    if row_dict['County Name'] or row_dict['Constituency Name']:
                        # If County Name or Constituency Name is
                        # present, this introduces a new county +
                        # constituency:
                        county_name = row_dict['County Name']
                        current_county_number = int(row_dict['County No.']) if re.search('^\d+$', c) else None
                        current_county_name = row_dict['County Name']
                        # There are a couple of special cases where
                        # the county name is in the wrong column:
                        if row_dict['Constituency Name'] == 'Isiolo North':
                            current_county_name = 'Isiolo'
                        elif row_dict['Constituency Name'] == 'Luanda':
                            current_county_name = 'Vihiga'
                            current_county_number = 38
                        current_constituency_name = row_dict['Constituency Name']
                        constituency_number_column = headings.index('Constituency No.') + 1
                        current_constituency_number = int(row[constituency_number_column])

                    else:
                        # Otherwise this is a row that gives details
                        # of the ward:
                        ward_number = row_dict['County Assembly Ward No.']
                        ward_name = row_dict['County Assembly Ward Name']

                        # The final line of the file has no ward
                        # details, so skip any such line:
                        if not ward_name:
                            continue

                        # print current_county_number, current_county_name, current_constituency_number, current_constituency_name, ward_number, ward_name

                        # The first of these seems likely to be a
                        # mistake, but we do this to match the
                        # constituency correctly:
                        fixes = {'Ol Joro Orok': 'Ol Jorok',
                                 'Mukurweni': 'Mukurweini',
                                 'Dagoreti North': 'Dagoretti North'}

                        fixed_constituency_name = fixes.get(current_constituency_name,
                                                            current_constituency_name)

                        constituency_slug = slugify(fixed_constituency_name) + '-2013'

                        constituency = Place.objects.get(kind__name='Constituency',
                                                         parliamentary_session=next_session,
                                                         slug=constituency_slug)

                        ward_slug = 'ward-' + slugify(ward_name)

                        try:
                            ward_place = Place.objects.get(slug=ward_slug)
                        except Place.DoesNotExist:
                            ward_place = Place(slug=ward_slug,
                                               name=ward_name.decode('utf-8'),
                                               kind=ward_place_kind,
                                               parent_place=constituency,
                                               parliamentary_session=next_session)
                        if options['commit']:
                            print >> sys.stderr, "Saving", ward_place
                            ward_place.save()
                        else:
                            print >> sys.stderr, "Not saving", ward_place, "because --commit wasn't specified"
    def handle(self, *args, **options):

        office_kind = OrganisationKind.objects.get(slug='constituency-office')

        if len(args) != 1:
            self.print_help(sys.argv[0], sys.argv[1])
            return

        office_id = args[0]

        if not options['new_address']:
            raise CommandError('You must supply --address')

        if (options['lat'] is None) ^ (options['lon'] is None):
            raise CommandError('You must supply both --lat and --lon')

        try:
            office = Organisation.objects.get(pk=office_id)
        except Organisation.DoesNotExist:
            raise CommandError("No office found with ID {0}".format(office_id))

        self.stdout.write(
            "Updating the constituency office: " + office.name.encode('utf-8')
        )

        if office.kind != office_kind:
            raise CommandError(
                "Organisation {0} isn't a constituency office".format(office_id)
            )

        if options['lat']:
            lon = options['lon']
            lat = options['lat']
        else:
            # Otherwise try to geocode the address:
            try:
                lon, lat, _ = geocode(options['new_address'])
                print "Location found"
            except LocationNotFound:
                raise CommandError(u"Couldn't find the location of:\n{0}".format(
                    options['new_address']
                ))

        # Check with the user if this is actually the location they
        # want:

        url_template = 'https://www.google.com/maps/place/{lat}+{lon}/@{lat},{lon},17z'
        print "This would update the office address to:"
        print ' ', url_template.format(lon=lon, lat=lat)
        print "If this is correct, type 'y' to continue:"
        response = raw_input('(y/n): ')
        if response != 'y':
            sys.stderr.write("Aborting.\n")
            return

        existing_positions = office.place_set.filter(
            kind__slug='constituency-office',
            name__startswith='Approximate position'
        )
        if len(existing_positions) > 1:
            msg = "Bad data: found multiple existing positions for the office"
            raise CommandError(msg)
        elif len(existing_positions) == 0:
            # Create a new position:
            position_name = u'Approximate position of ' + office.name
            position = Place(
                name=position_name,
                organisation=office,
                slug=slugify(position_name),
                location=Point(lon, lat),
                kind=PlaceKind.objects.get(slug='constituency-office'),
            )
        else:
            # Update the existing position:
            position = existing_positions[0]
            position.location = Point(lon, lat)

        existing_addresses = office.contacts.filter(kind__slug='address')
        if len(existing_addresses) > 1:
            msg = "Bad data: found multiple existing addresses for the office"
            raise CommandError(msg)
        elif len(existing_addresses) == 0:
            contact_address = Contact(
                value=options['new_address'],
                kind=ContactKind.objects.get(slug='address'),
            )
        else:
            contact_address = existing_addresses[0]
            contact_address.value = options['new_address']

        # Actually save to the database (or not, depending on whether
        # --commit was specified).

        if options['commit']:
            print "Saving to the database:"
        else:
            msg = "Not updating (--commit wasn't specified) but would save:"
            self.stdout.write(msg)
        self.stdout.write(
            'Place: ' + unicode(position).encode('utf-8')
        )
        self.stdout.write(
            'Contact: ' + unicode(contact_address).encode('utf-8')
        )

        if options['commit']:
            position.save()
            contact_address.save()
Example #4
0
    def handle_label(self, input_filename, **options):

        next_session = ParliamentarySession.objects.get(slug='na2013')

        # Get (or create) the PlaceKind for wards:

        try:
            ward_place_kind = PlaceKind.objects.get(slug='ward')
        except PlaceKind.DoesNotExist:
            ward_place_kind = PlaceKind(slug="ward",
                                        name="Ward",
                                        plural_name="Wards")
            name = str(ward_place_kind).encode('utf-8')
            if options['commit']:
                print >> sys.stderr, "Saving", name
                ward_place_kind.save()
            else:
                print >> sys.stderr, "Not saving", name, "because --commit wasn't specified"

        with open(input_filename) as fp:

            reader = csv.reader(fp)
            for row in reader:
                # The column headings change at various points in the
                # file, so save them when they appear:
                if re.search('County No', row[0]):
                    headings = [c.strip() for c in row]
                else:
                    # Otherwise create a dictionary that maps headings
                    # to column values:
                    row_dict = dict(zip(headings, (c.strip() for c in row)))
                    if row_dict['County Name'] or row_dict['Constituency Name']:
                        # If County Name or Constituency Name is
                        # present, this introduces a new county +
                        # constituency:
                        county_name = row_dict['County Name']
                        current_county_number = int(
                            row_dict['County No.']) if re.search('^\d+$',
                                                                 c) else None
                        current_county_name = row_dict['County Name']
                        # There are a couple of special cases where
                        # the county name is in the wrong column:
                        if row_dict['Constituency Name'] == 'Isiolo North':
                            current_county_name = 'Isiolo'
                        elif row_dict['Constituency Name'] == 'Luanda':
                            current_county_name = 'Vihiga'
                            current_county_number = 38
                        current_constituency_name = row_dict[
                            'Constituency Name']
                        constituency_number_column = headings.index(
                            'Constituency No.') + 1
                        current_constituency_number = int(
                            row[constituency_number_column])

                    else:
                        # Otherwise this is a row that gives details
                        # of the ward:
                        ward_number = row_dict['County Assembly Ward No.']
                        ward_name = row_dict['County Assembly Ward Name']

                        # The final line of the file has no ward
                        # details, so skip any such line:
                        if not ward_name:
                            continue

                        # print current_county_number, current_county_name, current_constituency_number, current_constituency_name, ward_number, ward_name

                        # The first of these seems likely to be a
                        # mistake, but we do this to match the
                        # constituency correctly:
                        fixes = {
                            'Ol Joro Orok': 'Ol Jorok',
                            'Mukurweni': 'Mukurweini',
                            'Dagoreti North': 'Dagoretti North'
                        }

                        fixed_constituency_name = fixes.get(
                            current_constituency_name,
                            current_constituency_name)

                        constituency_slug = slugify(
                            fixed_constituency_name) + '-2013'

                        constituency = Place.objects.get(
                            kind__name='Constituency',
                            parliamentary_session=next_session,
                            slug=constituency_slug)

                        ward_slug = 'ward-' + slugify(ward_name)

                        try:
                            ward_place = Place.objects.get(slug=ward_slug)
                        except Place.DoesNotExist:
                            ward_place = Place(
                                slug=ward_slug,
                                name=ward_name.decode('utf-8'),
                                kind=ward_place_kind,
                                parent_place=constituency,
                                parliamentary_session=next_session)
                        if options['commit']:
                            print >> sys.stderr, "Saving", ward_place
                            ward_place.save()
                        else:
                            print >> sys.stderr, "Not saving", ward_place, "because --commit wasn't specified"