Search code examples
djangodatabasedjango-modelsgeolocation

Storing the data in the console in a database and accessing it


I'm building a web app which accesses the location of the user when a particular button is pressed for this I'm using the HTML geolocation api.

Below is the location.js file:

`var x = document.getElementById("demo");
function getLocation() {
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(showPosition);
    } else {
        x.innerHTML = "Geolocation is not supported by this browser.";
    }
}
function showPosition(position) {
    x.innerHTML = "Latitude: " + position.coords.latitude +
    "<br>Longitude: " + position.coords.longitude;
    console.log(position.coords.latitude)
    console.log(position.coords.longitude)
}

Below is the snippet of the HTML file:

<button onclick="getLocation()">HELP</button>
<p id="demo"></p>
<script src="../static/location.js"></script>

What I want to do is send this information ( i.e. longitude/latitude of the user ) to list of e-mails associated with that user but I don't know how to store this data and access this after the button is pressed. It would be of great use if someone could get me started on how to save this data corresponding to the user and accessing it from the database.


Solution

  • If you want to store this info to a django DB, then if might be easier to do this in a django view. This could be a RedirectView that just redirects to the same view after the button is clicked.

    I have previously used a downloaded DB of the GeoLite2-City.mmdb, which might not always be up to date, but is ok.

    You can get the ip address of a request in django with the ipware library. Then convert it into a python IP object in IPy. You can then use the geoip library to get the information out of the DB.

    Import the following libraries;

    from ipware.ip import get_ip
    from IPy import IP
    import geoip2.database
    

    Then your method to get the IPs would be something like

    class MyRedirectView(RedirectView)
    
        def get_redirect_url(self, request, *args, **kwargs):
            ## Write some code to handle the redirect url first ##
    
            ip_address = get_ip(self.request)
    
            """Ensure that the IP address is a valid IP first"""
            try:
                IP(ip_address)
            except Exception:
                logger.exception("GEOIP2 error: ")
    
            """Then get the IP location"""
            geo_path = settings.GEOIP_PATH
            reader = geoip2.database.Reader(geo_path + '/GeoLite2-City.mmdb')
            try:
                response = reader.city(ip_address)
                city = response.city.name
                country = response.country.name
    
             ### Some code here to save to your DB
            return super(MyRedirectView, self).get_redirect_url(*args, **kwargs)
    

    If you need a much more accurate IP location service you could involce an API call to something like http://ip-api.com/. But then you would have to wait for this response before serving the next view.