E
E
Elvis2017-01-23 00:12:21
Django
Elvis, 2017-01-23 00:12:21

How to make a prepopulated field in a django model?

There is a field in which the city is entered. Next, there are 2 fields with the coordinates of this city, latitude and longitude.
It is necessary to make it so that when entering a city, a request is sent to Google and coordinates are inserted from the answer.
I know how to make a request to Google, for example like this:

address = "Москва"
api_key = "api key google"
api_response = requests.get('https://maps.googleapis.com/maps/api/geocode/json?address={0}&key={1}'.format(address, api_key))
api_response_dict = api_response.json()

if api_response_dict['status'] == 'OK':
    lat = api_response_dict['results'][0]['geometry']['location']['lat']
    lng = api_response_dict['results'][0]['geometry']['location']['lng']

How can I make sure that when creating a record after entering the city, the values ​​\u200b\u200bare immediately substituted in the bottom 2 fields of latitude and longitude?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
S
sim3x, 2017-01-23
@sim3x

You make a view that will send a request to Google
with Ajax you request it
Or you also request Google API directly with Ajax, and not from the server

A
Artem, 2017-01-23
@ulkoart

as one of the OPTIONS:
1. In the model you make a method for obtaining coordinates (def get_gps ... return lat, lng)
2. pre_save signal ...instance. lat = ...

E
Elvis, 2017-01-23
@Dr_Elvis

I decided this way:
- added, through the redefinition of the admin template, a button next to the city input field
- hung up the function of requesting coordinates:

(function($) { $(document).ready(function() {
  $("#id_to_city").after('<input type="button" value="Запросить координаты" onclick="get_geo(el(\'id_to_city\').value)"/>');
});
})(django.jQuery);

- wrote the function itself:
function get_geo(city) {
  var x = new XMLHttpRequest();
  var api_key = "google_api_key";
  var result = '';
  x.open("GET", "https://maps.googleapis.com/maps/api/geocode/json?address="+city+"&key="+api_key, true);
  x.onload = function (){
    result = JSON.parse(x.responseText);
    el("id_to_lat").value = result.results[0].geometry.location.lat;
    el("id_to_lng").value = result.results[0].geometry.location.lng;
  };
  x.send(null);
}

Now I write the city, I press the button and in a moment I have the coordinates of the city in the right place.
Thanks to all! the idea of ​​ajax led me to this decision.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question