{"id":593,"date":"2022-08-30T15:03:56","date_gmt":"2022-08-30T15:03:56","guid":{"rendered":"https:\/\/unknownerror.org\/index.php\/2013\/11\/09\/django-using-form-input-to-query-data-should-be-simple-isnt-for-me-collection-of-common-programming-errors\/"},"modified":"2022-08-30T15:03:56","modified_gmt":"2022-08-30T15:03:56","slug":"django-using-form-input-to-query-data-should-be-simple-isnt-for-me-collection-of-common-programming-errors","status":"publish","type":"post","link":"https:\/\/unknownerror.org\/index.php\/2022\/08\/30\/django-using-form-input-to-query-data-should-be-simple-isnt-for-me-collection-of-common-programming-errors\/","title":{"rendered":"Django using form input to query data &mdash; should be simple, isn&#39;t (for me)-Collection of common programming errors"},"content":{"rendered":"<p>I have a form which looks like this:<\/p>\n<pre><code>class AddressSearchForm(forms.Form):\n    \"\"\"\n        A form that allows a user to enter an address to be geocoded\n    \"\"\"\n    address = forms.CharField()\n<\/code><\/pre>\n<p>I&#8217;m not storing this value, however, I am geocoding the address and checking to make sure it is valid:<\/p>\n<pre><code>def clean_address(self):\n    address = self.cleaned_data[\"address\"]\n    return geocode_address(address, True)\n<\/code><\/pre>\n<p>The geocode function looks like this:<\/p>\n<pre><code>def geocode_address(address, return_text = False):\n    \"\"\" returns GeoDjango Point object for given address\n        if return_text is true, it'll return a dictionary: {text, coord}\n        otherwise it returns {coord}\n    \"\"\" \n    g = geocoders.Google()\n    try:\n        #TODO: not really replace, geocode should use unicode strings\n        address = address.encode('ascii', 'replace')            \n        text, (lat,lon) = g.geocode(address)\n        point = Point(lon,lat)\n   except (GQueryError):\n       raise forms.ValidationError('Please enter a valid address')\n    except (GeocoderResultError, GBadKeyError, GTooManyQueriesError):\n    raise forms.ValidationError('There was an error geocoding your address. Please try again')\n    except:\n        raise forms.ValidationError('An unknown error occured. Please try again')\n\n    if return_text:\n         address = {'text':text, 'coord':point}\n    else:\n        address = {'coord':point}\n\n    return address\n<\/code><\/pre>\n<p>What I now need to do is create a view that will query a model using the address data to filter the results. I&#8217;m having trouble figuring out how to do this. I&#8217;d like to use CBV&#8217;s if possible. I can use FormView to display the form, and ListView to display the query results, but how do I pass the form data between the two?<\/p>\n<p>Thanks in advance.<\/p>\n<p>UPDATE: I know how to query my model to filter the results. I just don&#8217;t know how to properly combine using a Form and Class Based Views so that I can access the cleaned_data for my filter. e.g:<\/p>\n<p>Process should be:<\/p>\n<p>1) Display form on get 2) Submit form and validate (geocode address) on post 3) Run query and display results<\/p>\n<pre><code>address = form.cleaned_data['address']\npoint = address['coord']\nqs = model.objects.filter(point__distance_lte=(point, distance)\n<\/code><\/pre>\n<ol>\n<li>\n<p>Ok, here&#8217;s a generic version of what ended up working based on psjinx direction:<\/p>\n<pre><code>from django.views.generic.base import TemplateResponseMixin, View\nfrom django.views.generic.edit import FormMixin\nfrom django.views.generic.list import MultipleObjectMixin\n\nclass SearchView(FormMixin, MultipleObjectMixin, TemplateResponseMixin, View):\n    \"\"\"\n     A View which takes a queryset and filters it via a validated form submission\n    \"\"\"\n    queryset = {{ initial queryset }} # you can use a model here too eg model=foo\n    form_class = {{ form }}\n\n    def get(self, request, *args, **kwargs):\n        form_class = self.get_form_class()\n        form = self.get_form(form_class)\n        return self.render_to_response(self.get_context_data(form=form))\n\n    def post(self, request, *args, **kwargs):\n        form_class = self.get_form_class()\n        form = self.get_form(form_class)\n        if form.is_valid():\n            return self.form_valid(form)\n        else:\n            return self.form_invalid(form)    \n\n    def form_valid(self, form):\n        queryset = self.get_queryset()\n        search_param = form.cleaned_data['{{ form field }}']\n        object_list = queryset.filter({{ filter operation }}=search_param)\n        context = self.get_context_data(object_list=object_list, form=form, search_param=search_param)\n        return self.render_to_response(context) \n<\/code><\/pre>\n<\/li>\n<\/ol>\n<p id=\"rop\"><small>Originally posted 2013-11-09 21:06:49. <\/small><\/p>","protected":false},"excerpt":{"rendered":"<p>I have a form which looks like this: class AddressSearchForm(forms.Form): &#8220;&#8221;&#8221; A form that allows a user to enter an address to be geocoded &#8220;&#8221;&#8221; address = forms.CharField() I&#8217;m not storing this value, however, I am geocoding the address and checking to make sure it is valid: def clean_address(self): address = self.cleaned_data[&#8220;address&#8221;] return geocode_address(address, True) [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[1],"tags":[],"class_list":["post-593","post","type-post","status-publish","format-standard","hentry","category-uncategorized"],"_links":{"self":[{"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/posts\/593","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/comments?post=593"}],"version-history":[{"count":0,"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/posts\/593\/revisions"}],"wp:attachment":[{"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/media?parent=593"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/categories?post=593"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/tags?post=593"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}