def clean(self): """clean attributes""" cleaned_data = self.cleaned_data where = cleaned_data.get('where') if where: if len(where.split()) < 3: # doesn't look like a whole address, looks like a place - find it from our places DB sq = SearchQuerySet().filter(content=where).filter(django_ct="reps.place") if len(sq) == 0: self._errors['where'] = self.error_class(['We couldn\'t find that place. Try providing some more detail.']) if len(sq) == 1: cleaned_data['place_id'] = sq[0].object.id else: self._errors['place_id'] = self.error_class(['There are more than one possible place with that name - which one did you mean?']) else: # likely a whole address, geocode it geocode = geocoder(settings.GOOGLE_MAPS_API_KEY, lonlat=True) location = geocode(where) if location[0]: try: district = District.objects.get(area__contains=Point(location[1])) cleaned_data['district_id'] = district.id except District.DoesNotExist, e: try: location = geocode("%s, Arizona, USA" % (cleaned_data['where'])) district = District.objects.get(area__contains=Point(location[1])) cleaned_data['district_id'] = district.id except District.DoesNotExist, e: self._errors['where'] = self.error_class(['We couldn\'t recognise that address - is it in Arizona?']) else: self._errors['where'] = self.error_class(['We couldn\'t recognise that address - is it a valid address?']) if location[1][0]: cleaned_data['lat'] = location[1][1] cleaned_data['lon'] = location[1][0]
def save(self, *args, **kwargs): geocode = geocoder(settings.GOOGLE_GEOCODER_KEY) location_data = geocode(str(self)) try: coords = location_data[1] self.latitude = str(coords[0]) self.longitude = str(coords[1]) except IndexError: pass super(Address, self).save(*args, **kwargs)