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

2023-04-21前端开发问题
7

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

问题描述

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

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.

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

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.

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

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.

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

I am currently up to here with my progress but still am unable to post the latitude and longitude to the django admin page:

代码如下:

django项目结构如下:

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)

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)

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

views.py (server)

from django.shortcuts import redirect

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

urls.py(服务器)

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

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

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.

推荐答案

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

I have used jQuery and Ajax to submit the longitude and latitude data to any model you want to store these data in.

在你的 model.py 中:

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)

为了你的 view.py

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('')

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

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)

最后是实际的形式,

  $(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 令牌才能提交表单.

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 admin?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

js删除数组中指定元素的5种方法
在JavaScript中,我们有多种方法可以删除数组中的指定元素。以下给出了5种常见的方法并提供了相应的代码示例: 1.使用splice()方法: let array = [0, 1, 2, 3, 4, 5];let index = array.indexOf(2);if (index -1) { array.splice(index, 1);}// array = [0,...
2024-11-22 前端开发问题
182

layui 实现实时刷新一个外部的div
主页面上显示了一个合计,在删除和增加的时候需要更改这个总套数的值: //html代码div class="layui-inline layui-show-xs-block" style="margin-left: 10px" id="sumDiv"spanSOP合计:/spanspan${totalNum}/spanspan套/span/div 于是在我们删除这个条数据后,...
2024-11-14 前端开发问题
156

layui要如何改变时间日历布局大小?
问题描述 我想改变layui时间日历布局大小,这个要怎么操作呢? 解决办法 可以用css样式对时间日历进行重新布局,具体代码如下: !DOCTYPE htmlhtmlheadmeta charset="UTF-8"title/titlelink rel="stylesheet" href="../../layui/css/layui.css" /style#test-...
2024-10-24 前端开发问题
271

JavaScript小数运算出现多位的解决办法
在开发JS过程中,会经常遇到两个小数相运算的情况,但是运算结果却与预期不同,调试一下发现计算结果竟然有那么长一串尾巴。如下图所示: 产生原因: JavaScript对小数运算会先转成二进制,运算完毕再转回十进制,过程中会有丢失,不过不是所有的小数间运算会...
2024-10-18 前端开发问题
301

jQuery怎么动态向页面添加代码?
append() 方法在被选元素的结尾(仍然在内部)插入指定内容。 语法: $(selector).append( content ) var creatPrintList = function(data){ var innerHtml = ""; for(var i =0;i data.length;i++){ innerHtml +="li class='contentLi'"; innerHtml +="a href...
2024-10-18 前端开发问题
125

JavaScript(js)文件字符串中丢失"\"斜线的解决方法
问题描述: 在javascript中引用js代码,然后导致反斜杠丢失,发现字符串中的所有\信息丢失。比如在js中引用input type=text onkeyup=value=value.replace(/[^\d]/g,) ,结果导致正则表达式中的\丢失。 问题原因: 该字符串含有\,javascript对字符串进行了转...
2024-10-17 前端开发问题
437