Как вставить переменную javascript в модель в Django? - PullRequest
0 голосов
/ 23 апреля 2019

Я пытаюсь сохранить долготу и широту пользователя в модели, которую можно использовать с различными API для таких вещей, как трафик и погода, а что нет.Я получаю широту и долготу пользователей с помощью navigator.geolocation, который находится в html5.Каков наилучший способ сохранить эту информацию в модели 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 и программировании в целом, а также в стеке потока, так что, если мне нужно включить более или менее, или мне нужно спросить об этом по-другому, пожалуйста, дайте мне знать!

1 Ответ

0 голосов
/ 23 апреля 2019

Предположим, у вас есть следующая модель пользователя:

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>

Обратите внимание на дополнительную функциональность jsascript csrftoken.

Это всего лишь один из способов сделать это. Конечно, есть и лучшие способы, используя django-rest-framework

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...