javascript - 如何将 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 的新手,所以如果我需要包含更多或更少的内容,或者应该以不同的方式提出这个问题,请告诉我!
解决方案
假设您有以下用户模型:
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当然有更好的方法
推荐阅读
- python - 如何检查创建一百万个 ndarray 所花费的时间?
- github - 获取组织中的 Github 存储库所有者
- javascript - Bootstrap 4 垂直药丸导航未按预期工作
- python - 你如何让不和谐机器人一遍又一遍地发送相同的消息(python)
- python - 从光栅文件中提取数据
- c++ - 为什么我会收到一条错误消息:“'Ninety' 没有匹配的函数调用”?
- sql - SQL查询在一行中选择父名和子名
- swift - Swift 如何显示最新的 Firebase 消息而不会出现故障滚动到最后一个索引
- python - 连接到 rabbitmq SSLError: [SSL: SSLV3_ALERT_HANDSHAKE_FAILURE] sslv3 警报握手失败 (_ssl.c:1108)
- javascript - 状态码 403 ...仅当来自我的服务器的请求不在本地时