2013-01-20 39 views
1

我有一個非常簡單的Django形式由單個領域 - 「地址」:Django的形式,地理編碼 - 在地理編碼,如何驗證,如何通過地址解析結果

class AddressSearchForm(forms.Form): 
    """ 
     A form that allows a user to enter an address to be geocoded 
    """ 
    address = forms.CharField() 

我可能甚至不需要使用表單,因爲我沒有保存這些數據 - 我只是將它收集起來用於搜索。但是,我想執行驗證:

def clean_address(): 
    data = self.cleaned_data 
    g = geocoders.Google() 
    try: 
     place, (lat,lng) = g.geocode(data['address']) 
    except (GQueryError): 
     raise forms.ValidationError('Please enter a valid address') 
    except (GeocoderResultError, GBadKeyError, GTooManyQueriesError): 
     raise forms.ValidationError('There was an error geocoding your address. Please  try again') 
    except: 
     raise forms.ValidationError('An unknown error occured. Please try again') 

另外,我想用這個地址解析結果的Point對象傳遞給我的看法:

from django.contrib.gis.geos import Point 
point = Point(lng, lat) 

我的問題是,如何通過既地址和點數據到我的觀點?我只能傳遞地址,然後在視圖中重新進行地理編碼,但那會重複代碼。那麼,如何從表單中傳遞點對象呢?我應該使用隱藏字段嗎?其他建議?提前致謝。

回答

1

我不是Django的專家,但是這是我做過什麼:

def clean_homeaddress(self): 
     in_address = self.cleaned_data['homeaddress']   
     place, self.cleaned_data['homelocation'] = address_to_latlng(in_address, True) 
     return place 

哦,順便說一下,看看下面的包裝。地理編碼器.Google不會正確處理Unicode字符串。有一個簡單的黑客可以刪除所有非ascii字符。我還沒有時間找出更好的解決方案。

def address_to_latlng(address, return_address = False): 
    """ returns GoeDjango POINT string value for given location (address) 
     if return_address is true, it'll return 2-tuple: (address, point) 
     otherwise it returns point 
    """ 
    g = geocoders.Google() 
    try: 
     #TODO: not really replace, geocode should use unicode strings 
     address = address.encode('ascii', 'replace')    
     place, latlng = g.geocode(address)    
    except Exception as e:    
     raise ValidationError(_(u"Incorrect location provided")) 
    point = 'POINT(%f %f)' % tuple(reversed(latlng)) 
    if return_address: 
     return (place, point)  
    return point 

的要求,有完整的代碼。這個會將該位置打印到輸出控制檯,並且會在會話中保留「已清除」(由Google返回)地址,以便在每次顯示錶單時將其顯示給用戶。

class GeoForm(forms.Form): 
    address = forms.CharField()  

    def clean_address(self): 
     in_address = self.cleaned_data['address']   
     place, self.cleaned_data['location'] = address_to_latlng(in_address, True) 
     return place 

class GeoView(FormView): 
    form_class = GeoForm 
    template_name = 'geoview.html' 
    success_url = '/sandbox/geo' 
    def get_initial(self): 
     if '_address' in self.request.session: 
      return {'address': self.request.session['_address']} 
     return {} 
    def form_valid(self,form): 
     print form.cleaned_data['location'] 
     self.request.session['_address'] = form.cleaned_data['address'] 
     return super(GeoView, self).form_valid(form) 
+0

謝謝。你的表單是什麼樣的?你如何通過homeaddress和homelocation? –

+0

另外,您如何在您的視圖中訪問這些數據? –

+1

而且,對於Django Point字符串,不應該先經度走? –