Ejemplo n.º 1
0
def detail(request, pk, format=None):
    """Detail page for choice/request."""
    choice = get_object_or_404(Choice, pk=pk)
    if not request.user in [choice.tutee, choice.tutor]:
        messages.error(request, 'This is not your request')
        return HttpResponseRedirect(reverse('choices.views.requests'))
    if request.method == 'POST' and request.user.profile.tutee:
        date       = request.POST.get('date')
        address    = request.POST.get('address')
        city_name  = request.POST.get('city_name')
        state_name = request.POST.get('state_name')
        try:
            month, day, year = date.split('/')
        except ValueError:
            date = None
        if date and address and city_name and state_name:
            date = datetime(int(year), int(month), int(day))
            address    = address.lower()
            city_name  = city_name.lower()
            state_name = state_name.lower()
            try:
                state = State.objects.get(name=state_name)
            except State.DoesNotExist:
                state = State(name=state_name)
                state.save()
            try:
                city = state.city_set.get(name=city_name)
            except City.DoesNotExist:
                city = City(name=city_name, state=state)
                city.save()
            choice.address = address
            choice.city    = city
            choice.state   = state
            if choice.day.value == int(date.strftime('%w')):
                choice.date = date
                messages.success(request, 
                    'Tutor has been notified of your date and place')
                # Create notification for channel with this choice
                try:
                    channel = Channel.objects.get(choice=choice)
                    channel.create_notification(request.user, 'update')
                except Channel.DoesNotExist:
                    pass
            else:
                messages.error(request, 
                    'Date must be a %s' % choice.day.name.title())
            choice.save()
            if format and format == '.json':
                data = {
                    'choice': choice.to_json(),
                }
                return HttpResponse(json.dumps(data), 
                    mimetype='application/json')
    d = {
        'choice': choice,
        'choice_notes': choice.choicenote_set.all().order_by('-created'),
        'title': '%s on %s at %s' % (choice.interest.name.title(),
            choice.day.name.title(), choice.hour.time_string()),
    }
    return render(request, 'choices/detail.html', add_csrf(request, d))
Ejemplo n.º 2
0
 def setUp(self):
     country = Country(
         population=0
     )
     country.save()
     city1 = City(
         name='city1',
         name_std='city1....',
         country=country,
         location=Point(0, 0, srid=4326),
         population=0,
     )
     city1.save()
     self.city2 = City(
         name='city2',
         name_std='city2....',
         country=country,
         location=Point(100, 100, srid=4326),
         population=0,
     )
     self.city2.save()
     self.city3 = City(
         name='city3',
         name_std='city3....',
         country=country,
         location=Point(1000, -1000, srid=4326),
         population=0,
     )
     self.city3.save()
Ejemplo n.º 3
0
    def setUp(self):
        country = Country(name="Empire anarchique du Bachibouzouc",
                          population=12000)
        country.save()
        region = Region(name="Province dépendante du Bazar", country=country)
        region.save()
        city1 = City(name="Trifouillis les Oies",
                     region=region,
                     country=country,
                     location=Point(42, 127),
                     population=42)
        city1.save()
        city2 = City(name="Montcuq",
                     region=region,
                     country=country,
                     location=Point(42, 127),
                     population=127)
        city2.save()
        data = {
            "username": "******",
            "email": "*****@*****.**",
            "password": "******"
        }
        response = self.client.post(register_url, data, format="json")

        data = {
            "username": "******",
            "password": "******",
        }
        response = self.client.post(login_url, data, format="json")
        token = response.data["auth_token"]
        self.client.credentials(HTTP_AUTHORIZATION='Token ' + token)
Ejemplo n.º 4
0
 def setUp(self):
     country = Country(population=0)
     country.save()
     city1 = City(
         name='city1',
         name_std='city1....',
         country=country,
         location=Point(0, 0, srid=4326),
         population=0,
     )
     city1.save()
     self.city2 = City(
         name='city2',
         name_std='city2....',
         country=country,
         location=Point(100, 100, srid=4326),
         population=0,
     )
     self.city2.save()
     self.city3 = City(
         name='city3',
         name_std='city3....',
         country=country,
         location=Point(1000, -1000, srid=4326),
         population=0,
     )
     self.city3.save()
Ejemplo n.º 5
0
class TestCommandAirports(TestCase):
    def setUp(self):
        country = Country(population=0)
        country.save()
        city1 = City(
            name='city1',
            name_std='city1....',
            country=country,
            location=Point(0, 0, srid=4326),
            population=0,
        )
        city1.save()
        self.city2 = City(
            name='city2',
            name_std='city2....',
            country=country,
            location=Point(100, 100, srid=4326),
            population=0,
        )
        self.city2.save()
        self.city3 = City(
            name='city3',
            name_std='city3....',
            country=country,
            location=Point(1000, -1000, srid=4326),
            population=0,
        )
        self.city3.save()

    def test_get_city(self):
        city = get_city('test', 1000, -1000)
        self.assertEqual(city, self.city3)

    def tearDown(self):
        pass
Ejemplo n.º 6
0
    def import_city(self):            
        uptodate = self.download_once('city')
        if uptodate and not self.force: return
        data = self.get_data('city')

        self.build_country_index()
        self.build_region_index()

        self.logger.info("Importing city data")
        for item in data:
            if not self.call_hook('city_pre', item): continue
            
            if item['featureCode'] not in city_types: continue

            city = City()
            try:
                city.id = int(item['geonameid'])
            except:
                continue
            city.name = item['name']
            city.kind = item['featureCode']
            city.name_std = item['asciiName']
            city.slug = slugify(city.name_std)
            city.location = Point(float(item['longitude']), float(item['latitude']))
            city.population = int(item['population'])
            city.timezone = item['timezone']
            try:
                city.elevation = int(item['elevation'])
            except:
                pass

            country_code = item['countryCode']
            try: 
                country = self.country_index[country_code]
                city.country = country
            except:
                self.logger.warning("{0}: {1}: Cannot find country: {2} -- skipping".format("CITY", city.name, country_code))
                continue

            region_code = item['admin1Code']
            try: 
                region = self.region_index[country_code + "." + region_code]
                city.region = region
            except:
                self.logger.warning("{0}: {1}: Cannot find region: {2} -- skipping".format(country_code, city.name, region_code))
                continue
            
            subregion_code = item['admin2Code']
            try: 
                subregion = self.region_index[country_code + "." + region_code + "." + subregion_code]
                city.subregion = subregion
            except:
                if subregion_code:
                    self.logger.warning("{0}: {1}: Cannot find subregion: {2} -- skipping".format(country_code, city.name, subregion_code))
                pass
            
            if not self.call_hook('city_post', city, item): continue
            city.save()
            self.logger.debug("Added city: {0}".format(city))
Ejemplo n.º 7
0
def load_cities():
  cs = get_cities()
  f = open("../list_of_cities.txt")
  eu = []
  for line in f:
    eu.append(line[1:-3])

  for c in cs:
    if any(c[1] in city for city in eu):
      add = City(name=c[1],country=c[0],long=0,lat=0)
      add.save()
Ejemplo n.º 8
0
class TestCommandAirports(TestCase):
    def setUp(self):
        country = Country(
            population=0
        )
        country.save()
        city1 = City(
            name='city1',
            name_std='city1....',
            country=country,
            location=Point(0, 0, srid=4326),
            population=0,
        )
        city1.save()
        self.city2 = City(
            name='city2',
            name_std='city2....',
            country=country,
            location=Point(100, 100, srid=4326),
            population=0,
        )
        self.city2.save()
        self.city3 = City(
            name='city3',
            name_std='city3....',
            country=country,
            location=Point(1000, -1000, srid=4326),
            population=0,
        )
        self.city3.save()

    def test_get_city(self):
        city = get_city('test', 1000, -1000)
        self.assertEqual(city, self.city3)

    def tearDown(self):
        pass
Ejemplo n.º 9
0
    def load_cities(self, city_file):
        #Emply the City table
        self.delete_cities()

        errors = {}
        errors["data"] = []
        errors["trailer"] = []
        #Traverse the cities line by line
        count = 0
        try:
            for line in city_file[:-1]:
                #Increment count to check against
                count += 1

                city = {}
                finds = list(re.search('(.{20})(.{20})(.{2})', line).groups())
                city["city_label"] = finds[0].strip()
                city["city_name"] = finds[1].strip()
                city["state"] = finds[2].strip()

                if not City.objects.filter(city_label=city["city_label"]):
                    db_city = City(**city)
                    db_city.save()
                else:
                    error = "City label, {}, is a duplicate".format(
                        city["city_label"])
                    log.error("error")
                    errors["data"].append(error)
        except Exception as e:
            log.error(str(e))
            errors["data"].append(
                "Please make sure your file if properly formatted")

        errors["trailer"] += self.load_trailer(city_file[-1], count)

        log.info("Cities Updated")
        return errors
Ejemplo n.º 10
0
    def load_cities(self, city_file):
        #Emply the City table
        self.delete_cities()

        errors = {}
        errors["data"] = []
        errors["trailer"] = []
        #Traverse the cities line by line
        count = 0
        try:
            for line in city_file[:-1]:
                #Increment count to check against
                count += 1

                city = {}
                finds = list(re.search('(.{20})(.{20})(.{2})',line).groups())
                city["city_label"] = finds[0].strip()
                city["city_name"] = finds[1].strip()
                city["state"] = finds[2].strip()

                if not City.objects.filter(city_label=city["city_label"]):
                    db_city = City(**city)
                    db_city.save()
                else:
                    error = "City label, {}, is a duplicate".format(city["city_label"])
                    log.error("error")
                    errors["data"].append(error)
        except Exception as e:
            log.error(str(e))
            errors["data"].append("Please make sure your file if properly formatted")


        errors["trailer"] += self.load_trailer(city_file[-1], count)

        log.info("Cities Updated")
        return errors
Ejemplo n.º 11
0
    def import_city(self):
        uptodate = self.download_once('city')
        if uptodate and not self.force: return
        data = self.get_data('city')

        self.build_country_index()
        self.build_region_index()

        self.logger.info("Importing city data")
        for item in data:
            if not self.call_hook('city_pre', item): continue

            if item['featureCode'] not in city_types: continue

            city = City()
            try:
                city.id = int(item['geonameid'])
            except:
                continue
            city.name = item['name']
            city.kind = item['featureCode']
            city.name_std = item['asciiName']
            city.slug = slugify(city.name_std)
            city.location = Point(float(item['longitude']),
                                  float(item['latitude']))
            city.population = int(item['population'])
            city.timezone = item['timezone']
            try:
                city.elevation = int(item['elevation'])
            except:
                pass

            country_code = item['countryCode']
            try:
                country = self.country_index[country_code]
                city.country = country
            except:
                self.logger.warning(
                    "{0}: {1}: Cannot find country: {2} -- skipping".format(
                        "CITY", city.name, country_code))
                continue

            region_code = item['admin1Code']
            try:
                region = self.region_index[country_code + "." + region_code]
                city.region = region
            except:
                self.logger.warning(
                    "{0}: {1}: Cannot find region: {2} -- skipping".format(
                        country_code, city.name, region_code))
                continue

            subregion_code = item['admin2Code']
            try:
                subregion = self.region_index[country_code + "." +
                                              region_code + "." +
                                              subregion_code]
                city.subregion = subregion
            except:
                if subregion_code:
                    self.logger.warning(
                        "{0}: {1}: Cannot find subregion: {2} -- skipping".
                        format(country_code, city.name, subregion_code))
                pass

            if not self.call_hook('city_post', city, item): continue
            city.save()
            self.logger.debug("Added city: {0}".format(city))
Ejemplo n.º 12
0
def edit(request, slug, format=None):
    """Edit user page."""
    profile = get_object_or_404(Profile, slug=slug)
    user    = profile.user
    if request.user != user:
        return HttpResponseRedirect(reverse('users.views.edit',
            args=[request.user.profile.slug]))
    if request.method == 'POST':
        profile_form = ProfileForm(request.POST, instance=profile)
        if profile_form.is_valid():
            profile = profile_form.save()
            if request.POST.get('phone'):
                profile.phone = request.POST.get('phone')[0:10]
                profile.save()
        city_name  = request.POST.get('city_name')
        state_name = request.POST.get('state_name')
        if city_name and state_name:
            city_name  = city_name.lower()
            state_name = state_name.lower()
            try:
                # Check to see if state exists
                state = State.objects.get(name=state_name)
                try:
                    # Check to see if city exists in that state
                    city = state.city_set.get(name=city_name)
                except City.DoesNotExist:
                    # If no city in that state exists, create one in that state
                    city = City(name=city_name, state=state)
                    city.save()
            except State.DoesNotExist:
                # If state does not exist, create one
                state = State(name=state_name)
                state.save()
                # Then create a city for that state
                city = City(name=city_name, state=state)
                city.save()
            profile.city = city
            profile.save()
        if format and format == '.json':
            data = {
                'user': profile.to_json(),
            }
            return HttpResponse(json.dumps(data), mimetype='application/json')
        messages.success(request, 'Profile updated')
        return HttpResponseRedirect(reverse('users.views.detail',
            args=[profile.slug]))
    days     = []
    day_ids  = [dayfree.day.pk for dayfree in user.dayfree_set.all()]
    hours_am = []
    hours_pm = []
    hour_ids = [hourfree.hour.pk for hourfree in user.hourfree_set.all()]
    if profile.tutor:
        for day in Day.objects.filter(value__gte=0, value__lte=6):
            button_class = ''
            if day.pk in day_ids:
                button_class = 'selected'
            days.append((day, button_class))
        for hour in Hour.objects.filter(value__gte=0, value__lte=23):
            button_class = ''
            if hour.pk in hour_ids:
                button_class = 'selected'
            if hour.value >= 0 and hour.value <= 11:
                hours_am.append((hour, button_class))
            elif hour.value >= 12 and hour.value <= 23:
                hours_pm.append((hour, button_class))
        hours_am.sort(key=lambda (x, c): x.value)
        hours_pm.sort(key=lambda (x, c): x.value)
    profile_form = ProfileForm(instance=profile)
    skills = [skill for skill in user.skill_set.all()]
    # Autocomplete source for city name
    if profile.city and profile.city.state:
        state_slug = profile.city.state.name.replace(' ', '-')
        city_autocomplete_source = reverse('cities.views.city_list',
            args=[state_slug])
    else:
        city_autocomplete_source = reverse('cities.views.city_list')
    d = {
        'city_autocomplete_source': city_autocomplete_source,
        'days': days,
        'hours_am': hours_am,
        'hours_pm': hours_pm,
        'profile_form': profile_form,
        'skills': sorted(skills, key=lambda x: x.interest.name),
        'title': 'Edit',
    }
    return render(request, 'users/edit.html', add_csrf(request, d))
Ejemplo n.º 13
0
import csv
from cities.models import City

with open('cities/cities.csv', newline='') as fp:
    reader = csv.reader(fp, delimiter='\t')
    header = next(reader)
    for row in reader:
        #print(row[1], row[2], row[3].replace(',',''))
        c = City(name=row[1],
                 country_id=row[2],
                 population=int(row[3].replace(',', '')))
        c.save()