Köver
Köver

Reputation: 381

Django - pass js variable to django view

My question is related to the Google Maps JavaScript API. More specific the autocomplete function.

I've added the autocomplete function as a search bar to my test site and this works fine, but now I want to pass the chosen paramater to a Django view. And here I'm stuck.

This is what I have in my template:

<script src="https://maps.googleapis.com/maps/api/js?sensor=false&libraries=places"></script>
<script type="text/javascript">
   function initialize() {
      var input = document.getElementById('searchTextField');
      var autocomplete = new google.maps.places.Autocomplete(input);
   }
   google.maps.event.addDomListener(window, 'load', initialize);
   google.maps.event.addListener(autocomplete, 'place_changed', function() {
   var place = autocomplete.getPlace();
   });
</script>

<form method="post" action="">{% csrf_token %}
    <input id="searchTextField" type="text" placeholder="Enter a location" autocomplete="on">
    <input type="submit" value="Search" class="postfix button"/>
</form>

And this in my view:

def homepage(request):
    if request.method == 'POST':
        location = request.POST
else:
    location = ''
return render_to_response('homepage.html', {'location':location}, context_instance = RequestContext(request))

What I want to do is to pass the variable 'place' to the variable 'location' in my Django view (the var place should contain the lat and lon, and this I want to use then further in Geodjango). The request.POST gives the following: <QueryDict: {u'csrfmiddlewaretoken': [u'4xp3nNwzeITb1zHhkBkSGlZSPtGwmuMB']}> But this I can't use.

Is it possible to pass the content of var place to the django view?

Thanks for the feedback!

EDIT: my workaround for the moment using geopy:

Template:

<input id="searchTextField" name="searchTextField" type="text" placeholder="Enter a location" autocomplete="on">

View:

if request.method == 'POST':
    location = request.POST.get('searchTextField')
    gn = geocoders.Google()  
    place, (lat, lng) = gn.geocode(location)

Still looking for a way to access the var place in the script. Is this possible?

Upvotes: 3

Views: 5724

Answers (1)

katy lavallee
katy lavallee

Reputation: 2771

First add a name attribute to your search input. Let's say you called it searchTextField like the id. Then you can do request.POST.get('searchTextField').

Upvotes: 3

Related Questions