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

时间:2023-04-21
本文介绍了如何将 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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

上一篇:Javascript GeoLocation 在 Chrome 上不起作用 下一篇:在谷歌地图中仅显示特定国家(地区)

相关文章