gpt4 book ai didi

Django 使用表单输入查询数据——应该很简单,不是(对我来说)

转载 作者:行者123 更新时间:2023-12-03 20:37:47 37 4
gpt4 key购买 nike

我有一个看起来像这样的表格:

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

我现在需要做的是创建一个 View ,该 View 将使用地址数据来查询模型以过滤结果。我很难弄清楚如何做到这一点。如果可能,我想使用 CBV。我可以用FormView来显示表单,用ListView来显示查询结果,但是如何在两者之间传递表单数据呢?

提前致谢。

更新:我知道如何查询我的模型来过滤结果。我只是不知道如何正确组合使用基于表单和类的 View ,以便我可以访问我的过滤器的cleaned_data。例如:

流程应该是:

1) 获取时显示表单
2)提交表格并在邮寄时验证(地理编码地址)
3) 运行查询并显示结果
address = form.cleaned_data['address']
point = address['coord']
qs = model.objects.filter(point__distance_lte=(point, distance)

最佳答案

好的,这是基于 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)

关于Django 使用表单输入查询数据——应该很简单,不是(对我来说),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14443107/

37 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com