我有一个看起来像这样的表格:
class AddressSearchForm(forms.Form):
"""
A form that allows a user to enter an address to be geocoded
"""
address = forms.CharField()
我没有存储这个值,但是,我正在对地址进行地理编码并检查以确保它有效:
def clean_address(self):
address = self.cleaned_data["address"]
return geocode_address(address, True)
地理编码函数如下所示:
def geocode_address(address, return_text = False):
""" returns GeoDjango Point object for given address
if return_text is true, it'll return a dictionary: {text, coord}
otherwise it returns {coord}
"""
g = geocoders.Google()
try:
#TODO: not really replace, geocode should use unicode strings
address = address.encode('ascii', 'replace')
text, (lat,lon) = g.geocode(address)
point = Point(lon,lat)
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')
if return_text:
address = {'text':text, 'coord':point}
else:
address = {'coord':point}
return address
我现在需要做的是创建一个视图,该视图将使用地址数据查询模型以过滤结果。我很难弄清楚如何做到这一点。如果可能的话,我想使用 CBV。我可以使用FormView来显示表单,使用ListView来显示查询结果,但是如何在两者之间传递表单数据呢?
提前致谢。
更新:我知道如何查询我的模型来过滤结果。我只是不知道如何正确组合使用基于表单和类的视图,以便我可以访问我的过滤器的cleaned_data。例如:
流程应该是:
1) 在 get 上显示表单 2) 在 post 上提交表单并验证(地理编码地址) 3) 运行查询并显示结果
address = form.cleaned_data['address']
point = address['coord']
qs = model.objects.filter(point__distance_lte=(point, distance)