Предположим, у вас есть следующая модель пользователя:
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