如何在Django中将模型数据传递到Javascript?

时间:2019-05-02 17:27:54

标签: javascript python django

我正在创建一个网站,该网站必须在地图上显示this之类的不同标记。我已经在名为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'

1 个答案:

答案 0 :(得分:0)

好的,我会在包含您的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)})