How to save HTML5 geolocation data to python Django admin?

﹥>﹥吖頭↗ 提交于 2019-12-06 13:29:35

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!