Django使用表单输入查询数据——应该很简单,不是吗';t(对我来说)
我有一个表格,看起来像这样:Django使用表单输入查询数据——应该很简单,不是吗';t(对我来说),django,forms,views,django-class-based-views,class-based-views,Django,Forms,Views,Django Class Based Views,Class Based Views,我有一个表格,看起来像这样: class AddressSearchForm(forms.Form): """ A form that allows a user to enter an address to be geocoded """ address = forms.CharField() def geocode_address(address, return_text = False): """ returns GeoDjango Poi
class AddressSearchForm(forms.Form):
"""
A form that allows a user to enter an address to be geocoded
"""
address = forms.CharField()
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
我没有存储此值,但是,我正在对地址进行地理编码并检查以确保其有效:
def clean_address(self):
address = self.cleaned_data["address"]
return geocode_address(address, True)
geocode函数如下所示:
class AddressSearchForm(forms.Form):
"""
A form that allows a user to enter an address to be geocoded
"""
address = forms.CharField()
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显示查询结果,但是如何在两者之间传递表单数据呢
提前谢谢
更新:我知道如何查询我的模型以过滤结果。我只是不知道如何正确地结合使用表单和基于类的视图,这样我就可以访问过滤器的已清理的数据。e、 g:
程序应为:
1) 在get上显示表单
2) 提交表格并邮寄验证(地理编码地址)
3) 运行查询并显示结果
address = form.cleaned_data['address']
point = address['coord']
qs = model.objects.filter(point__distance_lte=(point, distance)
这类似于这里提出的一个问题,或者我会说两个问题的组合
更新1 有用链接: 相关问题:
好的,这里有一个基于psjinx方向的通用版本:
from django.views.generic.base import TemplateResponseMixin, View
from django.views.generic.edit import FormMixin
from django.views.generic.list import MultipleObjectMixin
class SearchView(FormMixin, MultipleObjectMixin, TemplateResponseMixin, View):
"""
A View which takes a queryset and filters it via a validated form submission
"""
queryset = {{ initial queryset }} # you can use a model here too eg model=foo
form_class = {{ form }}
def get(self, request, *args, **kwargs):
form_class = self.get_form_class()
form = self.get_form(form_class)
return self.render_to_response(self.get_context_data(form=form))
def post(self, request, *args, **kwargs):
form_class = self.get_form_class()
form = self.get_form(form_class)
if form.is_valid():
return self.form_valid(form)
else:
return self.form_invalid(form)
def form_valid(self, form):
queryset = self.get_queryset()
search_param = form.cleaned_data['{{ form field }}']
object_list = queryset.filter({{ filter operation }}=search_param)
context = self.get_context_data(object_list=object_list, form=form, search_param=search_param)
return self.render_to_response(context)
这类似于问题1。然而,这个问题的答案是以硬编码的形式使用GET。我想使用一个带有POST的表单类,这样我就可以对字段进行验证。这个答案还显示了一个使用FBV的解决方案,但如果可能的话,我想使用CBV。我在这里找到了一些关于使用mixin做类似事情的有用信息:,但没有什么能完全回答我的用例。请查看我的更新答案。我添加了代码框架,非常适合您的查看。谢谢,这真的很有帮助。我会试试看能不能让它工作。好的。如果你遇到任何问题,请告诉我。