如何将HTML5地理位置数据保存到python Django管理员? [英] How to save HTML5 geolocation data to python Django admin?

查看:126
本文介绍了如何将HTML5地理位置数据保存到python Django管理员?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当用户使用地理位置网站时,是否可以将javascript html5地理位置纬度和经度保存到django管理员。网页目标是保存用户的经度和纬度值,以便稍后当用户再次登录时可以访问数据。



我发现了一个类似的问题被问到在stackoverflow几年前,但没有任何答案。链接是:将JavaScript GeoLocation数据保存到Django管理页面



如果有基于此代码链接的答案,那就太棒了。



另一个我读到的选项是创建一个html表单,并将表单设置为jQuery从javascript html5 geolocation生成的数据中自动填充。对于像我这样的初学者来说,这也很复杂。



无论是通过代码,教程,博客文章,示例还是链接,我都会感激不尽。我不希望提供所有的编程代码(虽然我确实从示例中学到了更多)但是如果有一些材料/示例我可以去实现我的编程任务会有所帮助。谢谢。



我目前正在使用我的进度,但仍然无法将经度和经度发布到django管理页面:



代码如下:



django项目的结构如下:

  -ajax 
- __pycache__
- 迁移
- __pycache__
0001_initial.py
__init__.py
- 静态
- css
- bootstrap.css
- 字体
- js
- script.js
- 模板
- ajax
- base.html
- index.html
- __init__.py
- admin.py
- apps.py
- models.py
- tests.py
- urls.py
- views.py

-server
- __pycache__
- __init__.py
- 设置.py
- urls.py
- views.py
- wsgi.py

-db.sqlite3
-ma nage.py

index.html

  {%extends'ajax / base.html'%} 
{%block body%}
< p>点击按钮获取坐标。< / p为H.
< button onclick =getLocation()>获取您的位置< / button>
< p id =demo>< / p>
< button type =buttonid =btn_submitclass =btn btn-primary form-controldisabled> Submit< / button>
{%endblock%}

script.js

  var pos; 

var $ demo;

函数getLocation(){
if(navigator.geolocation){
navigator.geolocation.getCurrentPosition(showPosition);
} else {
$ demo.text(此浏览器不支持地理定位。);
}
}

函数showPosition(position){
pos = position;
var {latitude,longitude} = pos.coords;
$ demo.html(纬度:$ {纬度}< br>经度:$ {经度}`);
$('#btn_submit')。attr(disabled,null);
}

$(文件).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-8name =viewportcontent =width = device-width,initial-scale = 1>
{%load static%}
< link rel =stylesheettype =text / csshref ={%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 - 使用Ajax的Django简单提交表单< / h3>
< hr style =border-top:1px点缀#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

来自django.db的导入模型

#在此创建模型。

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)

 来自django.shortcuts导入渲染,重定向
来自.models导入成员

def索引(请求):
返回渲染(请求) ,'ajax / index.html')

def insert(请求):
member = Member(latitude = request.POST ['latitude'],经度= request.POST ['经度'])
member.save()
返回重定向('/')

urls.py(ajax)

 来自django.conf.urls import url 
from。导入视图

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

views.py(server)

 来自django.shortcuts导入重定向

def index_redirect(请求):
返回重定向( '/ ajax /')

urls.py(server)

 来自django.conf.urls import url,包括
来自django.contrib import admin
from。导入视图

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

它POST了数据,但它没有出现在django admin中。我搜索了很多寻找答案的网站,但仍未找到任何网站。再次感谢您的帮助。

解决方案

我使用jQuery和Ajax将经度和纬度数据提交给您想要的任何模型将这些数据存储在。model中的

 来自django.contrib.auth import用户
类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']
经度= request.POST ['long']
UserGeoLocation.create(
user = request.user
纬度=纬度,
经度=经度,




返回HttpResponse('')

现在我们有了视图,我们可以设置一个url端点来提交帖子请求

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

最后是实际表格,

  $(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()
},
} );

最后一步,假设您使用了您链接的示例中的js代码,那么您可以将这些坐标值分配给将使用在用户单击按钮时触发的post请求提交的变量,此处的id是要从中提交数据的表单的ID,并且e.PreventDefault将停止发布数据时重新加载的页面。最后,django需要csrf令牌才能提交表单。


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.

解决方案

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.

这篇关于如何将HTML5地理位置数据保存到python Django管理员?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆