簡體   English   中英

將值從 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);
 }

在 html 內容被渲染/發送到客戶端后,單獨獲取 django 和視圖來讀取 html 內容而不進行網絡請求是不可能的。

您必須使用網絡與視圖進行通信,因此您可以讓一些 JS 向您的視圖發送請求或查看 django websockets 和通道。

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

您也可以使用 ajax 或如本答案中前面提到的那樣使用請求模塊並執行例如 POST 請求。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM