在客户端使用JQuery / AJAX函数发布到Django视图时,我有些困惑。
我想在用户按下radius
按钮时发布到filter
视图,该按钮过滤给定半径10或20 km的本地用户。
queryset
视图中的radius
应该采用request.user
lat lon
坐标以及10或20 km的预定义radius_km
。
如何将这些请求(lat, lon, radius
)发布到视图?
urls.py
urlpatterns = [
path('', connect_views.connect_home_view, name='connect_home'),
path('insert', connect_views.insert, name='insert'),
path('radius', connect_views.radius, name='radius'),
views.py
def connect_home_view(request):
return render(request, 'connect/home.html', context)
def insert(request):
location =
Location(latitude=request.POST['latitude'],
longitude=request.POST['longitude'], user = request.user)
location.save()
return JsonResponse({'message': 'success'})
def radius(request):
radius_km = request.data.get('radius', 0)
queryset = User.objects.annotate(
radius_sqr=pow(models.F('loc__latitude') -
request.user.loc.latitude, 2) +
pow(models.F('loc__longitude') -
request.user.loc.longitude, 2)
).filter(
radius_sqr__lte=pow(radius_km / 9, 2)
)
context = dict(location=queryset)
return render_to_response('connect/home.html', context)
models.py
class Location(models.Model):
latitude = models.DecimalField(max_digits=19,
decimal_places=16)
longitude = models.DecimalField(max_digits=19,
decimal_places=16)
user = models.OneToOneField(User,
on_delete=models.CASCADE, related_name='loc')
connect.html
<!-- request.user lat / lon and save to Location model -->
<script>
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;
$('#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("insert", data, function() {
alert("Location saved");
});
});
});
</script>
<h1>Connect with people near you.</h1>
<p id="demo"></p>
<button onclick="getLocation()" class="btn
btn-warning" id="confirm">Get location</button>
<button type="submit" id="btn_submit"
class="btn btn-success" disabled>submit location
</button>
<button type="submit" id="btn_radius"
class="btn btn-info" disabled>filter results </button>