1

I am using Google Place Autocomplete in django template. I have a search bar which will show prediction for places. When users clicks the search button, I want to pass the value which is in search bar to django URL.

Below is the code

<label for="locationTextField">Location</label>
<input id="locationTextField" type="text" size="50">

<a href="{% url 'filteredcars' city  %}" id= "output">Search</a> 

<script>
    function init() {
        var input = document.getElementById('locationTextField');
        var autocomplete = new google.maps.places.Autocomplete(input);
        google.maps.event.addListener(autocomplete, 'place_changed', function f1() {
            var place = autocomplete.getPlace();
            var city = place.address_components[0].short_name;
            document.getElementById("output").innerHTML = city;
        });
     }
    google.maps.event.addDomListener(window, 'load', init);
</script>

I am able to get the city and show it in a HTML page, but I am not able to pass it as parameter in URL.

Can someone please give me any suggestions?

nik_m
  • 10,549
  • 4
  • 39
  • 52
Parth Shihora
  • 55
  • 1
  • 7

1 Answers1

1

Instead of having a different URL for each city (i.e /url/to/city1, /url/to/city2 etc) a much better approach is to have a single URL (i.e /url/to/city) and pass the city as a GET parameter (i.e /url/to/city/?name=city1). Do not let the GET (? character) discourage you. It is perfectly valid and quite self-explanatory (i.e when the resource /url/to/city is given a GET parameter - city name -, say amsterdam, it will serve a page with that city).

Enough with the theory, let's dive into code.

The a's href attribute will be:

<a href="{% url 'filteredcars' %}" id= "output">Search</a>

Inside script and above init() insert this handy function (taken from here):

function updateQueryStringParam(uri, key, value) {
  var re = new RegExp("([?&])" + key + "=.*?(&|$)", "i");
  var separator = uri.indexOf('?') !== -1 ? "&" : "?";
  if (uri.match(re)) {
    return uri.replace(re, '$1' + key + "=" + value + '$2');
  }
  else {
    return uri + separator + key + "=" + value;
  }
}

and then below var city = ..., insert:

output = document.getElementById("output");
output.href = updateQueryStringParam(output.href, 'name', city);
output.innerHTML = city;

Now, each time the event place_changed is triggered, the href will be updated to this format: /url/to/city/?name=<value_entered>

By doing this, you need to update the relevant code inside both urls.py and views.py files to handle the extra GET parameter (not too much to change, though ;). Share you code, if you don't know how.

nik_m
  • 10,549
  • 4
  • 39
  • 52