首页 > 解决方案 > 如何将 javascript 变量插入到 Django 中的模型中?

问题描述

我正在尝试将用户的经度和纬度保存到模型中,以便与各种 API 一起使用,例如交通和天气等。我通过使用 html5 中的 navigator.geolocation 获取用户的纬度和经度。将此信息保存到 UserProfile 模型的最佳方法是什么?

我已尝试设置要使用的表单,但无法使用启用地理定位的复选框进行任何操作。我也想过使用ajax,但不知道如何将数据传递给django中的模型。

<script type="text/javascript">
    $(document).ready(function(){
        $('input[type="checkbox"]').click(function(){
            if($(this).prop("checked") == true){
                getLocation()
            }
            else if($(this).prop("checked") == false){
                console.log("Location services are disabled");
            }
        });
    });
  function getLocation() {
    if (navigator.geolocation) {
      navigator.geolocation.getCurrentPosition(showPosition);
    } else { 
      console.log("Geolocation is not supported by this browser.");
    }
  }
    function showPosition(position) {
        console.log("Latitude: " + position.coords.latitude + 
        " Longitude: " + position.coords.longitude);
        var latlon = (position.coords.latitude + ','+ position.coords.longitude)
        console.log(latlon)

    };

这就是我用来获取用户位置的方法,它位于我为用户设置的 profile.html 页面中。我是 Django 和一般编码以及 stackoverflow 的新手,所以如果我需要包含更多或更少的内容,或者应该以不同的方式提出这个问题,请告诉我!

标签: javascriptpythondjango

解决方案


假设您有以下用户模型:

class UserProfile(AbstractUser):
    latitude = models.FloatField(null=True, blank=True)
    longitude = models.FloatField(null=True, blank=True)

在设置中指定

AUTH_USER_MODEL = "theapp.UserProfile"

我们需要创建一个处理它的视图:

from django.views.generic import DetailView
from django.http.response import HttpResponse
from .models import UserProfile

class UserView(DetailView):
    template_name = "profile.html"
    model = UserProfile
    context_object_name = 'profile'

    def post(self, request, *args, **kwargs):

        profile = self.get_object()
        lat = request.POST.get("latitude")
        long = request.POST.get("longitude")

        if lat is None or long is None:
            return HttpResponse()

        profile.latitude = float(lat)
        profile.longitude = float(long)
        profile.save()

        return HttpResponse()

然后模板如下:

<div>
    <strong>Current lat: </strong> {{ profile.latitude }}<br/>
    <strong>Current long: </strong> {{ profile.longitude }}<br/><br/>
</div>

<label for="locations-status">Locations enabled?</label>
<input type="checkbox" id="locations-status">

<script
  src="https://code.jquery.com/jquery-3.4.0.min.js"
  integrity="sha256-BJeo0qm959uMBGb65z40ejJYGSgR7REI4+CW1fNKwOg="
  crossorigin="anonymous"></script>

<script>
    var PROFILE_ID = {{ profile.id }};

</script>

<script type="text/javascript">

    function getCookie(name) {
        var cookieValue = null;
        if (document.cookie && document.cookie !== '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = cookies[i].trim();
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) === (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }

    var csrftoken = getCookie('csrftoken');

    $(document).ready(function(){
        $('input[type="checkbox"]').click(function(){
            if($(this).prop("checked") == true){
                getLocation()
            }
            else if($(this).prop("checked") == false){
                console.log("Location services are disabled");
            }
        });

        $.ajaxSetup({
            beforeSend: function(xhr, settings) {
                if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
                    xhr.setRequestHeader("X-CSRFToken", csrftoken);
                }
            }
        });
    });

    function csrfSafeMethod(method) {
        // these HTTP methods do not require CSRF protection
        return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
    }

    function getLocation() {
        if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(showPosition);
        } else {
            console.log("Geolocation is not supported by this browser.");
        }
    }

    function showPosition(position) {
        console.log("Latitude: " + position.coords.latitude + " Longitude: " + position.coords.longitude);
        var latlon = (position.coords.latitude + ','+ position.coords.longitude);

        $.post({
            url: "{% url 'profile-detail' profile.id %}",
            data: {
                latitude: position.coords.latitude,
                longitude: position.coords.longitude,
            }
        });

        console.log(latlon);
    };
</script>

注意额外的 csrftoken javascript 功能。

这只是一种方法。使用django-rest-framework当然有更好的方法


推荐阅读