繁体   English   中英

如何在django中将模型数据传递给Javascript?

[英]how to Pass model data to Javascript in django?

我创建一个网站,我必须拿出地图就像不同的标记 我已经在名为City的模型中保存了纬度,经度,city_name和country_name,现在我想要的是在Javascript中访问此模型数据以添加标记。
我已经尝试将Python数据转换为JSON,但我不能,因为我不知道如何做到这一点。 我已经找到了解决方案,但它们都非常令人困惑,因为我不知道将Python数据转换为JSON和序列化器。

这是我的代码:

 {% extends "map/base.html"%} {% block content%} <div id="map"></div> <script> var map; function initMap() { map = new google.maps.Map(document.getElementById('map'), { center: {lat: 30.3753, lng: 69.3451}, zoom: 6 }); //declare marker call it 'i' var marker, i; //declare infowindow var infowindow = new google.maps.InfoWindow(); //add marker to each locations var locations = {{marker}} for (i = 0; i < locations.length; i++) { marker = new google.maps.Marker({ position: new google.maps.LatLng(locations[i][1], locations[i][2]), map: map, icon: locations[i][3] }); //click function to marker, pops up infowindow google.maps.event.addListener(marker, 'click', (function(marker, i) { return function() { infowindow.setContent(locations[i][0]); infowindow.open(map, marker); } })(marker, i)); } } //initmap end google.maps.event.addDomListener(window, 'load', initialize); </script> {% endblock%} 

 from django.shortcuts import render from .models import City import json from django.forms.models import model_to_dict # Create your views here. def map(request): marker = City.objects.all() for item in marker: print(item) item = model_to_dict(item) marker = json.dumps(marker) context_dict['marker']= marker context = { 'marker': context_dict, } return render (request, "map/index.html", context) 

 from django.db import models class City(models.Model): country = models.CharField("Country",max_length=100, blank=False) city = models.CharField("City",max_length=100, blank=False) lan = models.DecimalField("Latitude",max_digits=15, decimal_places=8, blank=False) lng = models.DecimalField("Longitude",max_digits=15, decimal_places=8, blank=False) def __str__(self): return self.city +"-"+ self.country class Meta: # order of drop-down list items ordering = ('country',) # plural form in admin view verbose_name_plural = 'cities' 

好的,我会在数组中包含你的lan和lng。 然后我将这个var渲染为模板中的javascript变量。

def map(request):
    marker = City.objects.all()
    array_of_array = []
    for item in marker:
        array_of_array.append([item.lan,item,lng])
    return render (request, "map/index.html", {'marker': str(array_of_array)})

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM