Search code examples
javascriptpythondjangohtmlgeolocation

How to save HTML5 geolocation data to python Django admin?


Is it possible to save the javascript html5 geolocation latitude and longitude to the django admin when user uses the geolocation website. The web page goal is to save the user's longitude and latitude values so that the data can be accessed later on when user signs in again.

I found a similar question being asked in stackoverflow years ago but there hasn't been any answer. The link is : Save JavaScript GeoLocation data to Django admin page

It would be great if there this an answer based on this code link.

Another option I read about is to create a html form and set the form to be autopopulated by jQuery from data produced by the javascript html5 geolocation. Again this is quite complicated for a beginner like me.

I would appreciate any bit of help whether by code, tutorial, blog post, examples or links. I don't expect all the programming code to be provided (although I do learn better from examples) but it would help if there are some material/example I could go to, to implement my programming tasks. Thank you.

I am currently up to here with my progress but still am unable to post the latitude and longitude to the django admin page:

code is as following:

The structure of the django project is as follows:

-ajax
   - __pycache__
   - migrations
        - __pycache__
          0001_initial.py
          __init__.py
   - static
        - css
            - bootstrap.css
        - fonts
        - js
            - script.js
   - templates
        - ajax
            - base.html
            - index.html
        - __init__.py
        - admin.py
        - apps.py
        - models.py
        - tests.py
        - urls.py
        - views.py

-server
   - __pycache__
   - __init__.py
   - settings.py
   - urls.py
   - views.py
   - wsgi.py

-db.sqlite3
-manage.py

index.html

{% extends 'ajax/base.html' %}
{% block body %}
<p>Click the button to get your coordinates.</p>
<button onclick="getLocation()">Get Your Location</button>
<p id="demo"></p>
<button type="button" id="btn_submit" class="btn btn-primary form-control" disabled>Submit</button>
{% endblock %}

script.js

var pos;

var $demo;

function getLocation() {
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(showPosition);
  } else {
    $demo.text("Geolocation is not supported by this browser.");
  }
}

function showPosition(position) {
  pos = position;
  var { latitude, longitude } = pos.coords;
  $demo.html(`Latitude: ${latitude}<br>Longitude: ${longitude}`);
  $('#btn_submit').attr("disabled", null);
}

$(document).ready(function() {
  $demo = $("#demo");
  $('#btn_submit').on('click', function() {
    var data = pos.coords;
    data.csrfmiddlewaretoken = $('input[name=csrfmiddlewaretoken]').val();
    $.post("/ajax/", data, function() {
      alert("Saved Data!");
    });
  });
});

base.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8" name="viewport" content="width=device-width, initial-scale=1">
    {% load static %}
    <link rel="stylesheet" type="text/css" href="{% static 'ajax/css/bootstrap.css' %}"/>
</head>
<body>
    {% csrf_token %}
    <nav class="navbar navbar-default">
        <div class="container-fluid">
        </div>
    </nav>
    <div class="col-md-3"></div>
    <div class="col-md-6 well">
        <h3 class="text-primary">Python - Django Simple Submit Form With Ajax</h3>
        <hr style="border-top:1px dotted #000;"/>
        {% block body %}
        {% endblock %}
    </div>
</body>
<script src = "{% static 'ajax/js/jquery-3.2.1.js' %}"></script>
<script src = "{% static 'ajax/js/script.js' %}"></script>
</html>

models.py

from django.db import models

# Create your models here.

class Member(models.Model):
    latitude = models.DecimalField(max_digits=19, decimal_places=16)
    longitude = models.DecimalField(max_digits=19, decimal_places=16)

views.py (ajax)

from django.shortcuts import render, redirect
from .models import Member

def index(request):
    return render(request, 'ajax/index.html')

def insert(request):
    member = Member(latitude=request.POST['latitude'], longitude=request.POST['longitude'])
    member.save()
    return redirect('/')

urls.py (ajax)

from django.conf.urls import url
from . import views

urlpatterns = [
    url(r'^$', views.index, name="index"),
    url(r'^insert$', views.insert, name="insert")
]

views.py (server)

from django.shortcuts import redirect

def index_redirect(request):
    return redirect('/ajax/')

urls.py (server)

from django.conf.urls import url, include
from django.contrib import admin
from . import views

urlpatterns = [
    url(r'^$', views.index_redirect, name="index_redirect"),
    url(r'^ajax/', include("ajax.urls")),
    url(r'^admin/', admin.site.urls),
]

It "POST"s the data but it does not appear in the django admin. I trawled many websites searching for answers why but still haven't found any. Thank you again for your help.


Solution

  • I have used jQuery and Ajax to submit the longitude and latitude data to any model you want to store these data in.

    in your model.py:

        from django.contrib.auth import User
        class UserGeoLocation(models.Model):
    
             user = models.OneToOneField(User)
             latitude = models.FloatField(blank=False, null=False)
             longitude = models.FloatField(blank=False, null=False)
    

    for your view.py

        def save_user_geolocation(request):
    
             if request.method == 'POST':
                 latitude = request.POST['lat']
                 longitude = request.POST['long']
                 UserGeoLocation.create(
                      user = request.user
                      latitude= latitude,
                      longitude = longitude,
    
    
                  )
    
                return HttpResponse('')
    

    now that we have the view we can setup a url endpoint to submit the post request

      url('^abc/xyz/$', appname.views.save_user_geolocation)
    

    and Finally for the actual form,

      $(document).on('submit', '#id', function(e){
          e.preventDefault();
          $.ajax(
    
           type='POST',
           url = 'abc/xyz',
           data : {
    
               lat:position.coords.latitude,
               long: position.coords.longitude
               csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val()
             },
            });
    

    for the last step, lets say you used the js code from the example you linked, then you can assign these coordinates value to variables that will be submitted with the post request that gets triggered when the user clicks on the button, the id here is the id of the form you want to submit the data from, and the e.PreventDefault is to stop the page from reloading when you post the data. Finally, the csrf token is required by django to able to submit the form.