javascript - 如何将 HTML5 地理位置数据保存到 python Django admin?

标签 javascript python django html geolocation

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

几年前我在 stackoverflow 中发现了一个类似的问题,但没有任何答案。链接是:Save JavaScript GeoLocation data to Django admin page

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

我读到的另一个选项是创建一个 html 表单,并将该表单设置为由 jQuery 根据 javascript html5 地理定位生成的数据自动填充。同样,这对于像我这样的初学者来说非常复杂。

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

目前我的进度已经到这里了,但仍然无法将纬度和经度发布到 django 管理页面:

代码如下:

django项目结构如下:

-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 %}

脚本.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!");
    });
  });
});

基础.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>

模型.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(服务器)

from django.shortcuts import redirect

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

urls.py(服务器)

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),
]

它“发布”了数据,但它没有出现在 django 管理中。我搜索了很多网站来寻找答案,但仍然没有找到任何答案。再次感谢您的帮助。

最佳答案

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

在你的 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)

为你的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('')

现在我们有了 View ,我们可以设置一个 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 代码,然后您可以将这些坐标值分配给变量,这些变量将与用户单击按钮时触发的发布请求一起提交,这里的 id 是您要从中提交数据的表单的 id,e.PreventDefault 是在您发布数据时停止页面重新加载。最后,django 需要 csrf token 才能提交表单。

关于javascript - 如何将 HTML5 地理位置数据保存到 python Django admin?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50626626/

相关文章:

javascript - 未找到隧道 URL,回退到 LAN URL

javascript - 延迟中断 javascript 重定向

python - 投资组合优化的蒙特卡罗方法

javascript - 导入对象时,fs.readFileSync 不是函数

javascript - 根据视口(viewport)宽度更改 fullCalendar View 和标题选项?

python - Seaborn 图 - X 轴上的错误日期

python - 检测当前shell是否为python中的powershell

Django:将extra_context传递到reset_password View 并接收给定模板中的extra_context

python - Django QuerySet.filter(property__regex ='^This not autocomplete' ) 的 VSCode 自动完成

python - 具有已存在表的 Django ManyToMany 字段