How to save HTML5 geolocation data to python Django admin?

后端 未结 1 864
孤街浪徒
孤街浪徒 2021-01-16 11:51

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 u

1条回答
  •  无人共我
    2021-01-16 12:28

    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.

    0 讨论(0)
提交回复
热议问题