Skip to content Skip to sidebar Skip to footer

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 l

Solution 1:

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

defsave_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.longitudecsrfmiddlewaretoken:$('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.

Post a Comment for "How To Save Html5 Geolocation Data To Python Django Admin?"