将值从 html 模板传递到 Django 中的 views.py

Passing a value from html template to views.py in Django

你能帮我解决我遇到的问题吗? 基本上,我按照在线教程创建了一个基于位置的应用程序,该应用程序显示用户所在位置周围的商店。但是,用户的经度和纬度是硬编码在 views.py 中的。

views.py 

from django.http import request, HttpResponse
from django.views import generic
from django.contrib.gis.geos import Point
from django.contrib.gis.db.models.functions import Distance
from .models import Shop


longitude = 10.113
latitude = -2.231
user_location = Point(longitude, latitude, srid=4326)


class Home(generic.ListView):
    model = Shop
    context_object_name = 'shops'
    queryset = Shop.objects.annotate(distance=Distance('location',
    user_location)
    ).order_by('distance')[0:15]
    template_name = 'shops/index.html'

我在我的模板中添加了 Leaflet 集成,所以现在我可以访问用户的纬度和经度变量,我需要将这些变量传回我的 views.py 并在那里更新它们。这在一般情况下可能吗?您是什么解决方案? 非常感谢您的帮助

index.html

map.locate({setView: true, maxZoom: 16});

function onLocationFound(e)
 {
   var radius = e.accuracy;
   var lat = e.latlng.lat;
   var lon = e.latlng.lng;
   L.marker(e.latlng).addTo(map)
           .bindPopup("You are within " + radius + " meters from this point"+  +lat+lon).openPopup();
            L.circle(e.latlng, radius).addTo(map);
 }

在不进行网络请求的情况下,让 django 和视图单独读取 html 内容是不可能的。

您必须使用网络与视图通信,因此您可以让一些 JS 向您的视图发送请求或查看 django websockets 和通道。

https://channels.readthedocs.io/en/latest/

您也可以使用 ajax 或如前文所述使用请求模块并执行例如POST 个请求。